<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>This.props.children</title> <script src="../reactJs/react.development.js"></script> <script src="../reactJs/react-dom.development.js"></script> <script src="../reactJs/babel.min.js"></script> <style> </style> </head> <body> <div id="root"></div> </body> <script type="text/babel"> /* * this.props对象中属性,与组件上的属性完全一致, 但是 this.props.children是个例外,它表示组件的所有子节点(这个子节点 像是vue中的slot啊) * * */ class NoteList extends React.Component { render() { return ( <ol> { React.Children.map(this.props.children, (item, index) => { return <li>{item} + {index}</li>; }) } </ol> ) } } ReactDOM.render( <NoteList> <span>Alex</span> <span>Rate</span> </NoteList>, document.getElementById('root') ) /* * 这里需要注意: * 1.this.props.children的值有三种可能 如果当前组件没有节点,它就是undefined;如果有一个子节点,它的数据类型就是Object;如果是有多个子节点,数据类型就是Array.因此处理this.props.children的时候要特别的小心 * 2.React提供一个工具方法 React.Children来处理this.props.children. 我们可以使用React.Children.map来遍历子节点,而不用担心this.props.children的数据类型是undefined还是Object. * * * */ </script> </html>
React学习 --- 二.Props组件传值
最新推荐文章于 2025-04-08 10:36:37 发布