一种方法是使用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