加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React学习(五)this.props.children

发布时间:2020-12-15 07:11:57 所属栏目:百科 来源:网络整理
导读:this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性。 它表示组件的所有子节点上面代码的 NoteList 组件有两个 span 子节点,它们都可以通过 this.props.children 读
this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性。

它表示组件的所有子节点上面代码的 NoteList 组件有两个 span 子节点,它们都可以通过 this.props.children 读取。

<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="D:/ReactDom/build/react.min.js"></script>
    <script src="D:/ReactDom/build/react-dom.min.js"></script>
    <script src="D:/ReactDom/build/browser.min.js"></script>
  </head>
<body>
    <div id="example"></div>
    <script type="text/babel">
      var NotesList = React.createClass({
        render: function() {
          return (
            <ol>
              {
                React.Children.map(this.props.children,function (child) {
                  return <li>{child}</li>;
                })
              }
            </ol>
          );
        }
      });

      ReactDOM.render(
        <NotesList>
          <span>hello</span>
          <span>world</span>
        </NotesList>,document.getElementById('example')
      );
    </script>
  </body>
</html>

运行结果:

1.hello

2.world


这里需要注意, this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。所以,处理 this.props.children 的时候要小心。 React 提供一个工具方法 React.Children 来处理 this.props.children 。我们可以用 React.Children.map 来遍历子节点,而不用担心 this.props.children 的数据类型是 undefined 还是 object。更多的 React.Children 的方法,请参考官方文档。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读