JavaScript如何将道具传递给{this.props.children}

JavaScript如何将道具传递给{this.props.children},第1张

JavaScript如何将道具传递给{this.props.children}

Cloning children with new props

您可以使用React.Children遍历子级,然后使用React.cloneElement使用新的道具(浅合并)克隆每个元素,例如:

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 childrenWithProps = React.Children.map(this.props.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'));

Calling children as a function

您也可以将道具传递给带有渲染道具的孩子。在这种方法中,子代(可以是

children
或任何其他prop名称)是一个函数,可以接受您要传递的任何参数并返回子代:

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() {    // Note that children is called as a function and we can pass args to it    return <div>{this.props.children(this.doSomething)}</div>  }};ReactDOM.render(  <Parent>    {doSomething => (      <React.Fragment>        <Child doSomething={doSomething} value="1" />        <Child doSomething={doSomething} value="2" />      </React.Fragment>    )}  </Parent>,  document.getElementById('container'));

如果您愿意,也可以代替

<React.Fragment>
或简单地
<>
返回一个数组。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5509133.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存