美文网首页
react中props.children和React.Child

react中props.children和React.Child

作者: 野蛮生长_ed2e | 来源:发表于2018-05-05 18:24 被阅读0次

一、this.props.children

this.props对象的属性与组件的属性一一对应,但是有一个例外,就是this.props.children属性,它代表组件的所有子节点,举一个官方的🌰

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.body
);

NotesList组件的两个span子节点,都可以通过this.props.children获取,这里需要注意, this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。所以,处理 this.props.children 的时候要小心。

二 、React.Children

如果想把父组件的属性传给所有子组件就要用到React.Children属性了🌰

//子组件

function RadioOption(props) {

return (

<label>

<input type="radio" value={props.value} name={props.name} />

{props.label}

</label>

)

}
function renderChildren(props) {//遍历所有子组件
return React.Children.map(props.children, child => {

if (child.type === RadioOption)

return React.cloneElement(child, {

//克隆每一个对象,并且把父组件的props.name赋值给每个子组件

name: props.name

})

else

return child

})

}


//父组件

function RadioGroup(props) {

return (

<div>

{renderChildren(props)}

</div>

)

}
function App() {

return (

<RadioGroup name="hello">

<RadioOption label="选项一" value="1" />

<RadioOption label="选项二" value="2" />

<RadioOption label="选项三" value="3" />

</RadioGroup>

)

}

export default App

相关文章

网友评论

      本文标题:react中props.children和React.Child

      本文链接:https://www.haomeiwen.com/subject/yzlerftx.html