React源码阅读1Fork最新版React源码地址刚开始看源码,先过一遍。先看顶层暴露的API,再具体看实现的源码。保持学习。React入口constReact={Children:{map,forEach,count,toArray,only,},createRef,Component,PureComponent,createContext,forwardRef,lazy,memo,useCallback,useContext,useEffect,useImperativeHandle,useDebugValue,useLayoutEffect,useMemo,useReducer,useRef,useState,片段:REACT_FRAGMENT_TYPE,探查器:REACT_PROFILER_TYPE,严格模式:REACT_STRICT_MODE_TYPE,悬念:REACT_SUSPENSE_TYPE,不稳定的悬念列表:REACT_SUSPENSE_LIST_TYPE,createElement:__DEV__?createElementWithValidation:createElement,cloneElement:__DEV__?cloneElementWithValidation:cloneElement,createFactory:__DEV__?createFactoryWithValidation:createFactory,isValidElement:isValidElement,版本:ReactVersion,unstable_withSuspenseConfig:withSuspenseConfig,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ReactSharedInternals,};exportdefaultReact;ChildrenReact.Children提供了使用this.props.children不透明数据结构的实用方法//React.jsimport{forEach,map,count,toArray,only}from'./ReactChildren';......Children:{map,forEach,count,toArray,only,},//ReactChildren,jsexport{forEachChildrenasforEach,mapChildrenasmap,countChildrenascount,onlyChildasonly,toArray,};React.Children复制代码.map在children中的每个直接子级上调用一个函数并将其设置为thisArg。如果children是一个数组,它将被迭代并为数组中的每个子节点调用函数。如果子节点为null或undefined,此方法将返回null或undefined而不是数组。如果children是一个Fragment对象,会被当成一个单独的子节点,不会被遍历。render(){return();}映射源函数mapChildren(children,func,context){if(children==null){返回孩子;}//返回结果数组constresult=[];//result进去转了一圈,这里就不细说了mapIntoWithKeyPrefixInternal(children,result,null,func,context);返回结果;}https://segmentfault.com/a/11...写的比较详细它不返回数组。forEach源代码/***遍历通常指定为`props.children`的子项。**请参阅https://reactjs.org/docs/react-api.html#reactchildrenforeach**将为每个*叶子级调用提供的forEachFunc(child,index)。**@param{?*}children子树容器。*@param{function(*,int)}forEachFunc*@param{*}forEachContextforEachContext的上下文。*/functionforEachChildren(children,forEachFunc,forEachContext){if(children==null){返回孩子;}consttraverseContext=getPooledTraverseContext(null,null,forEachFunc,forEachContext,);traverseAllChildren(孩子,forEachSingleChild,traverseContext);releaseTraverseContext(traverseContext);}React.Children.countReact.Children.count(children)返回children中的组件总数,等同于通过map或forEach调用回调次数的次数。count源码functioncountChildren(children){returntraverseAllChildren(children,()=>null,null);}React.Children.onlyReact.Children.only(children)验证children是否只有一个子节点(一个React元素),如果是则返回它,否则该方法会抛出错误。onlysourcefunctiononlyChild(children){invariant(isValidElement(children),'React.Children.onlyexpectedtoreceiveasingleReactelementchild.',);returnchildren;}React.Children.only()不接受React.Children.map()的返回值,因为它是数组而不是React元素。React.Children.toArrayReact.Children.toArray(children)将复杂的数据结构children展平并返回为数组,并为每个子节点分配一个key。当你想在渲染函数中操作子集合时,这很有用,特别是当你想重新排序内容或在传递this.props.children之前获取子集时。React.Children.toArray()更改键值以在展平扩展子项列表时保留嵌套数组的语义。也就是说,toArray会为返回数组中的每个key加上一个前缀,让每个元素key的范围都限定在这个函数入参组的对象中。toArray源函数toArray(children){constresult=[];mapIntoWithKeyPrefixInternal(孩子,结果,空,孩子=>孩子);返回结果;}