子 props 的類型

2019-08-14 14:31 更新

通常,一個(gè)組件的子代(this.props.children)是一個(gè)組件的數(shù)組:

var GenericWrapper = React.createClass({
  componentDidMount: function() {    console.log(Array.isArray(this.props.children)); // => true
  },

  render: function() {    return <div />;
  }
});

React.render(  <GenericWrapper><span/><span/><span/></GenericWrapper>,
  mountNode
);

然而,當(dāng)只有一個(gè)子代的時(shí)候,this.props.children 將會(huì)變成一個(gè)單獨(dú)的組件,而不是數(shù)組形式。這樣就減少了數(shù)組的占用。

var GenericWrapper = React.createClass({
  componentDidMount: function() {    console.log(Array.isArray(this.props.children)); // => false

    // 注意:結(jié)果將是 5,而不是 1,因?yàn)?nbsp;`this.props.children` 不是數(shù)組,而是 'hello' 字符串!
    console.log(this.props.children.length);
  },

  render: function() {    return <div />;
  }
});

React.render(<GenericWrapper>hello</GenericWrapper>, mountNode);

為了讓處理 this.props.children 更簡(jiǎn)單,我們提供了 React.Children utilities。



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)