一種方法是使用React.Children迭代孩子,並使用React.cloneelement使用React.cloneelement將每個元素克隆到每個元素上。但是,由於潛在的代碼脆弱性,不建議使用此方法。
function sayHello(childName) {
console.log(`Hello from ${childName} the child`);
}
const childrenWithProps = React.Children.map(children, child => {
if (react.isvalidelement(child)){ 返回react.Cloneelement(child,{sayhello}); } return child;
});
return
function App() {
// Less type-safe but simpler alternative
console.log(`Hello from ${childName} the child`);
}
if (React.isValidElement(child)) { return React.cloneElement(child, { sayHello }); } return child;
For passing down properties to children, consider the following替代方案:
:創建一個跨組件的數據,無用的關係。 props
:在包裝器組件中定義渲染prop,並將其傳遞給子組件作為將props作為輸入的函數。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3