React children 抛出 PropTypes 错误
React children throw PropTypes error
我想知道如何在将组件作为 child:
传递时处理 PropTypes 错误
Failed prop type: The prop `value` is marked as required in `ChildComponent`, but its value is `undefined`.
渲染器按预期工作,并且正确传递了 value 属性。
我想发生这种情况是因为我将组件放在 App
组件的渲染函数中,没有任何道具。
当 ParentComponent
映射到其 children(即 ChildComponent)时,我仅将这些道具传递给 ChildComponent
。
查看代码:https://codesandbox.io/embed/r70r5z3j9q
有没有办法防止这种情况发生?
我应该如何构建我的组件?
我不应该将组件作为 children 传递吗?
已编辑:将道具 "name" 更改为 "value"。给它一个更通用的感觉。
我试图简化代码中的问题。
我知道我可以直接在 App
中传递 prop。
用例是 parent 正在进行计算并且这些计算应该传递给 child。没有明确知道这些 children 是什么。
这就是为什么我首先将它用作 child 的原因。
您正在使用 cloneElement
并且您将 prop 传递给它,而不是原始元素。要修复它,直接传递道具:
const App = () => (
<div>
<ParentComponent>
<ChildComponent name="bob" />
</ParentComponent>
</div>
);
您可以轻松地将组件作为 prop(不是子项)传递给您 ParentComponent
并仅在进行大量计算后才渲染它:
const App = () => (
<div>
<ParentComponent component={ChildrenComponent} />
</div>
);
const ParentComponent extends React.Component {
state = { heavyComputationFinished: false } // initial state
componentDidMount() {
runYourHeavyComputations
.then(() => { this.setState({ heavyComputationsFinished: true }) })
}
render() {
const { component } = this.props
const { heavyComputationsFinished, name } = this.state
// return nothing if heavy computations hasn't been finished
if (!heavyComputationsFinished) { return null }
// we're getting this component (not its rendering call) as a prop
return React.render(component, { name })
}
}
我想知道如何在将组件作为 child:
传递时处理 PropTypes 错误Failed prop type: The prop `value` is marked as required in `ChildComponent`, but its value is `undefined`.
渲染器按预期工作,并且正确传递了 value 属性。
我想发生这种情况是因为我将组件放在 App
组件的渲染函数中,没有任何道具。
当 ParentComponent
映射到其 children(即 ChildComponent)时,我仅将这些道具传递给 ChildComponent
。
查看代码:https://codesandbox.io/embed/r70r5z3j9q
有没有办法防止这种情况发生? 我应该如何构建我的组件? 我不应该将组件作为 children 传递吗?
已编辑:将道具 "name" 更改为 "value"。给它一个更通用的感觉。
我试图简化代码中的问题。
我知道我可以直接在 App
中传递 prop。
用例是 parent 正在进行计算并且这些计算应该传递给 child。没有明确知道这些 children 是什么。
这就是为什么我首先将它用作 child 的原因。
您正在使用 cloneElement
并且您将 prop 传递给它,而不是原始元素。要修复它,直接传递道具:
const App = () => (
<div>
<ParentComponent>
<ChildComponent name="bob" />
</ParentComponent>
</div>
);
您可以轻松地将组件作为 prop(不是子项)传递给您 ParentComponent
并仅在进行大量计算后才渲染它:
const App = () => (
<div>
<ParentComponent component={ChildrenComponent} />
</div>
);
const ParentComponent extends React.Component {
state = { heavyComputationFinished: false } // initial state
componentDidMount() {
runYourHeavyComputations
.then(() => { this.setState({ heavyComputationsFinished: true }) })
}
render() {
const { component } = this.props
const { heavyComputationsFinished, name } = this.state
// return nothing if heavy computations hasn't been finished
if (!heavyComputationsFinished) { return null }
// we're getting this component (not its rendering call) as a prop
return React.render(component, { name })
}
}