Cloning children with new props
(用新道具克隆儿童)
You can use React.Children to iterate over the children, and then clone each element with new props (shallow merged) using React.cloneElement eg:
(您可以使用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')
);
Fiddle: https://jsfiddle.net/2q294y43/2/
(小提琴: https : //jsfiddle.net/2q294y43/2/)
Calling children as a function
(称呼孩子为功能)
You can also pass props to children with render props .
(您也可以将道具传递给带有渲染道具的孩子。)
In this approach the children (which can be children
or any other prop name) is a function which can accept any arguments you want to pass and returns the children:(在这种方法中,子代(可以是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() {
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')
);
Instead of <React.Fragment>
or simply <>
you can also return an array if you prefer.
(除了<React.Fragment>
或简单地<>
您还可以根据需要返回一个数组。)
Fiddle: https://jsfiddle.net/ferahl/y5pcua68/7/
(小提琴: https : //jsfiddle.net/ferahl/y5pcua68/7/)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…