繁体   English   中英

反应孩子抛出PropTypes错误

[英]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函数中而没有任何道具。 我只是路过这些道具的ChildComponentParentComponent映射在它的孩子(这是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM