【问题标题】:React children throw PropTypes error反应儿童抛出 PropTypes 错误
【发布时间】:2018-05-09 11:49:56
【问题描述】:

我想知道,将组件作为子组件传递时如何处理 PropTypes 错误:

Failed prop type: The prop `value` is marked as required in `ChildComponent`, but its value is `undefined`.

渲染按预期工作,并且正确传递了 value 属性。

我想这是因为我将组件放入 App 组件的渲染函数中而没有任何道具。 当ParentComponent 映射到其子级(即 ChildComponent)时,我只会将这些道具传递给ChildComponent

查看代码:https://codesandbox.io/embed/r70r5z3j9q

有没有办法防止这种情况发生? 我应该如何构建我的组件? 我不应该将组件作为孩子传递吗?

已编辑:将道具“名称”更改为“值”。给它一个更一般的感觉。 我试图简化代码中的问题。 我知道我可以直接在App 中传递道具。 用例是当父母进行计算并且这些计算应该传递给孩子时。在没有明确知道这些孩子是什么的情况下。 这就是为什么我首先将它用作孩子。

【问题讨论】:

  • 在 ChildComponent.js 的第 7 行,您将 prop name 设置为必需。 name: PropTypes.string.isRequired。要么在 index.js 的 <ChildComponent /> 内提供 prop,要么不使 name 成为必需的 prop。

标签: javascript reactjs react-proptypes


【解决方案1】:

您正在使用 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 })
  }
}

【讨论】:

  • 我知道在这个例子中似乎没有必要在父级中添加道具。但是,如果我在父级内部做了一些计算或复杂的工作,我想传递给子级呢?
  • @SlootSantos 我改变了答案
  • 是的!这看起来更像是我可以转移到我的问题的东西!伟大的!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多