【问题标题】:React Component wait for required props to renderReact 组件等待所需的道具渲染
【发布时间】:2016-09-15 11:27:55
【问题描述】:

我在父组件内部声明一个组件。我想在一个文件中建立特定的道具,然后在父组件中,我希望能够一次为子组件建立其他道具(因为它们是共享属性......在大多数情况下)。

我的问题是子组件尝试渲染并失败,因为最初没有建立所需的道具类型。

有没有办法告诉子组件等待所需的道具渲染?

在 ParentComponent 渲染函数中,我调用另一个函数来运行 React.Children.map() 并将 props 附加到 ChildComponent。

渲染子组件的(粗略)部分:

<ParentComponent>
    <ChildComponent
        attribute="test_attribute"
        label="Child Component"
        type="number"
        width={3}
    />
</ParentComponent>

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您可以使用conditional render statement 仅在填充道具时渲染孩子:

let {foo, bar} = this.props;

<ParentComponent>
    { foo && bar ? <ChildComponent foo={foo} bar={bar} /> : null }
</ParentComponent>

或者代替null,您可以渲染&lt;LoadingSpinner /&gt; 或其他东西。

【讨论】:

猜你喜欢
  • 2023-04-01
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 2022-11-21
  • 1970-01-01
  • 2019-04-19
  • 2021-12-13
相关资源
最近更新 更多