【问题标题】:React HOC, instanceof, wrapped with?React HOC,instanceof,用什么包裹?
【发布时间】:2017-10-11 21:11:30
【问题描述】:

我使用 HOC 和 Redux 中的 compose 方法将组件包装在组件中。一个简单的例子:

const Textinput = class Textinput extends Component {
   ...
}

export default compose(
  Theme,
  Validator,
)(Textinput);

react 渲染的结果是:

<theme>
  <validator>
    <textinput />

想象另一个带有这个子组件的组件:

<Textinput />
<span>Test</span>
<Select />
<br/>

Textinput 和 Select 使用 HOC 包装在 Theme/Validator 组件中。我想枚举这个组件中的每个元素:

const children = React.Children.map(this.props.children, (child) => {

} 

但是:

  1. 如何知道渲染的元素是否包含在特定组件(如验证器或主题)中?

  2. 如何知道元素后面的组件是 Select 还是 Textinput 的 instanceof(而不是 Theme)?

【问题讨论】:

  • 如果您控制 HOC,您也可以将该信息作为道具传递。另外,您是否尝试过检查孩子们的displayName 属性?

标签: reactjs redux


【解决方案1】:

另一种解决方案是在每个 HOC 对象上添加一个新属性,例如:

Theme.innerInstances = {
  instance: WrappedComponent,
  innerInstances: WrappedComponent.innerInstances,
};

Validator.innerInstances = {
  instance: WrappedComponent,
  innerInstances: WrappedComponent.innerInstances,
};

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多