[英]React children throw PropTypes error
我想知道,將組件作為子代傳遞時如何處理PropTypes錯誤:
Failed prop type: The prop `value` is marked as required in `ChildComponent`, but its value is `undefined`.
渲染工作正常,並且正確傳遞了值prop。
我想發生這種情況是因為我將組件放置在App
組件的render函數中而沒有任何道具。 我只是路過這些道具的ChildComponent
當ParentComponent
映射在它的孩子(這是ChildComponent)。
看到代碼: https : //codesandbox.io/embed/r70r5z3j9q
有辦法防止這種情況發生嗎? 我應該如何構造我的組件? 我不應該小時候通過組件嗎?
編輯:將道具“名稱”更改為“值”。 給它更一般的感覺。 我試圖簡化代碼中的問題。 我知道我可以直接在App
傳遞道具。 用例是當父母在進行計算並且應該將這些計算傳遞給孩子時。 沒有明確知道這些孩子是什么。 這就是為什么我首先將其用作兒童的原因。
您正在使用cloneElement
並且將prop傳遞給它,而不是原始元素。 要解決此問題,請直接傳遞道具:
const App = () => (
<div>
<ParentComponent>
<ChildComponent name="bob" />
</ParentComponent>
</div>
);
您可以輕松地將組件作為道具(而不是子組件)傳遞給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 })
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.