React: 通过React.Children访问特定子组件
一、简介
React中提供了很多常用的API,其中有一个React.Children可以用来访问特定组件的子元素。它允许用来统计个数、map映射、循环遍历、转换数组以及显示指定子元素,如下所示:
var React = { // Modern Children: { map: ReactChildren.map, //映射 forEach: ReactChildren.forEach,//遍历 count: ReactChildren.count, //个数 toArray: ReactChildren.toArray,//转换数组 only: onlyChild //显示子组件 }, Component: ReactComponent, //组件 createElement: createElement, //创建节点 cloneElement: cloneElement, //克隆节点 isValidElement: ReactElement.isValidElement, //验证节点 // Classic PropTypes: ReactPropTypes, //类型验证 createClass: ReactClass.createClass, //创建组件类 createFactory: createFactory, //创建工厂类 createMixin: function (mixin) { //创建视图扩展类 // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, //节点文档 version: ReactVersion, //版本号 // Hook for JSX spread, don't use this for anything else. __spread: assign };
二、使用
需求:根据条件,根组件会选择需要显示的子组件进行展示。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Hello React</title> <script src="react/react.js"></script> <script src="react/react-dom.js"></script> <script src="react/browser.min.js"></script> </head> <body> <div id="container"></div> <script type="text/babel"> const targetNode = document.getElementById("container"); //结构赋值,作用域本地化 const {Children, propTypes} = React; const {render} = ReactDOM; //过滤函数,通过过滤将不符合条件的子组件去除,只会返回特定的子组件进行显示 const showChild = (children, child) => Children.toArray(children).filter(c => c.type === child)[0]; //下面是无状态函数式组件,children为根组件的孩子组件数组 //差劲:子组件 const PoorChild = ({children}) => Children.only(children); //中等:子组件 const MediumChild = ({children}) => Children.only(children); //优秀:子组件 const GoodChild = ({children}) => Children.only(children); //展示:根组件,会根据分数显示对应的孩子组件 const Display = ({score, children}) => { console.log(children); if (score>=0 && score < 60) return showChild(children, PoorChild); if (score >=60 && score < 85) return showChild(children, MediumChild); if (score >=85 && score <= 100) return showChild(children, GoodChild); }; //【0 , 60):差劲 [60 , 85):中等 [85 , 100]:优秀 const score = 88; render( <div> <Display score={score}> <PoorChild> <h1>my score is poor!</h1> </PoorChild> <MediumChild> <h1>my score is medium!</h1> </MediumChild> <GoodChild> <h1>my score is good!</h1> </GoodChild> </Display> </div>, targetNode ) </script> </body> </html>
可以看到三个子组件,只有优秀组件显示出来 :
可以看到子元素数组children的结构如下所示:
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!