React组件等待所需道具进行渲染

React Component wait for required props to render

本文关键字:组件 等待 React      更新时间:2023-09-26

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

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

有没有一种方法可以告诉子组件等待所需的道具渲染?

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

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

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

您可以使用条件呈现语句仅在填充道具时呈现子项:

let {foo, bar} = this.props;
<ParentComponent>
    { foo && bar ? <ChildComponent foo={foo} bar={bar} /> : null }
</ParentComponent>

或者,您可以渲染<LoadingSpinner />或其他内容来代替null