
將 Props 傳遞給 {this.props.children}
定義接受子元素的通用元件時,有必要將特定屬性傳遞給所有這些子元件。在 React 元件範例中,這是透過使用 {this.props.children} 來實現的。然而,問題出現了:如何傳遞這些屬性?
使用新道具克隆子元素
React.Children 提供了一個實用程式來迭代和克隆子元素,讓您可以建立修改後的子元素帶有新props 的版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const Child = ({ childName, sayHello }) => <button onClick={() => sayHello(childName)}>{childName}</button>;
function Parent({ children }) {
function sayHello(childName) {
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 <div>{childrenWithProps}</div>;
}
|
登入後複製
注意:一般不建議使用由於其潛在的脆弱性和潛在的類型安全問題,請使用cloneElement方法。
以上是如何在 React 中將 Props 傳遞給子元件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!