1. 程式人生 > >React學習(五)this.props.children

React學習(五)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 的方法,請參考官方文件。