React使用cloneElement向children传递props出现undefined报错如何解决
错误原因
- 组件层级关系颠倒:当前
Migration是父组件,内部渲染DataWrapper,DataWrapper接收的children是<div>hello</div>,cloneElement实际是给这个div元素添加test属性,Migration组件本身不可能收到该prop。 - 传递方向不符合默认规则:React默认遵循单向数据流,只能从父组件向子组件传props,你想让作为子组件的
DataWrapper给父组件Migration传值,不能通过给children加prop的方式实现。
解决方案
方案1:调整层级,符合容器组件使用逻辑
如果你就是要把DataWrapper作为通用容器,给内部包裹的业务组件传公共props,直接把Migration作为DataWrapper的children传入即可:
DataWrapper代码保持不变:
export default function DataWrapper(props) { return ( <DashboardWrapper> {cloneElement(props.children, { test: "hello there" })} </DashboardWrapper> ); }
- 移除
Migration内部的DataWrapper包裹,在父级调用处嵌套:
// 你渲染Migration的父组件代码 <DataWrapper> <Migration /> </DataWrapper>
- 调整后的
Migration代码:
export default function Migration(props) { console.log("props.test"); console.log(props.test); // 正常输出 hello there return <div>hello</div>; }
方案2:不调整层级,改用render props写法
如果你需要保持Migration包裹DataWrapper的层级结构,可以把children改成函数形式接收参数:
- 修改
DataWrapper代码:
export default function DataWrapper(props) { return ( <DashboardWrapper> {/* 执行children函数,把需要传递的参数传入 */} {props.children({ test: "hello there" })} </DashboardWrapper> ); }
- 调整后的
Migration代码:
export default function Migration() { return ( <DataWrapper> {(wrapperProps) => { console.log("props.test"); console.log(wrapperProps.test); // 正常输出 hello there return <div>hello</div>; }} </DataWrapper> ); }
内容的提问来源于stack exchange,提问作者mmz
相关产品推荐
相关产品推荐

