【问题标题】:How can I get a HOC to expose defaultProps of WrappedComponent to parent?如何让 HOC 将 WrappedComponent 的 defaultProps 暴露给父级?
【发布时间】:2018-11-01 15:44:02
【问题描述】:

我有一个 React 父级,它与 children 道具一起使用。现在,它只看到 Component 的内联 props 而不是 defaultProps。我也扩充了父元素以读取子元素 defaultProps。

渲染看起来像这样:

<Parent>
  <HOC>
    <Child_Element_With_Default_Props />
  </HOC>
</Parent>

问题是子元素周围有一个 HOC,它隐藏了 defaultProps。

有没有办法让 Parent 访问 Child 的 defaultProps?

【问题讨论】:

    标签: reactjs higher-order-components


    【解决方案1】:

    如果我正确理解了您的问题,您应该能够将 defaultProps 添加到 HOC 返回的组件中:

    const hoc = (Wrapped) => {
       const newComp = () => <Wrapped />
       newComp.defaultProps = Wrapped.defaultProps;
       return newComp;
    }
    

    (尚未测试此代码,但应该可以)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-06
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 2015-10-26
      • 2017-01-06
      相关资源
      最近更新 更多