Home >Web Front-end >JS Tutorial >How to Efficiently Pass Props to this.props.children in React?
In React, you may encounter a scenario where you want to use a wrapper component to encapsulate a group of child components and pass down some common properties to them.
One approach is to use React.Children to iterate over the children and clone each element with the new props using React.cloneElement. However, this method is not recommended due to potential code fragility.
<br>const Child = ({ childName, sayHello }) => (<br> <button onClick={() => sayHello(childName)}>{childName}</button><br>);</p> <p>function Parent({ children }) {<br> function sayHello(childName) {</p> <pre class="brush:php;toolbar:false">console.log(`Hello from ${childName} the child`);
}
const childrenWithProps = React.Children.map(children, child => {
if (React.isValidElement(child)) { return React.cloneElement(child, { sayHello }); } return child;
});
return
function App() {
// Less type-safe but simpler alternative
return (
<Parent> <Child childName="Billy" /> <Child childName="Bob" /> </Parent>
);
}
ReactDOM.render(
For passing down properties to children, consider the following alternatives:
The above is the detailed content of How to Efficiently Pass Props to this.props.children in React?. For more information, please follow other related articles on the PHP Chinese website!