react children技巧总结

在使用该技巧时,建议先看一下相关的知识,点我查看
 
假如使用该属性时,想把父组件的所有属性及部分方法传递给子组件,该怎么办呢?看代码

 const Child = ({ doSomething, value }) => (
  <div onClick={() => doSomething(value)}>Click Me</div>
);

class Parent extends React.PureComponent {
  doSomething = (value) => {
    console.log('doSomething called by child with value:', value);
  }

  render() {
    const { children } = this.props.children;

 const childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { doSomething: this.doSomething }) ); return <div>{childrenWithProps}</div>
  }
};

ReactDOM.render(
  <Parent>
    <Child value="1" />
    <Child value="2" />
  </Parent>,
  document.getElementById('container')
);

转载于猿2048:➦《react children技巧总结》

评论

暂无评论