【问题标题】:How to get HOC in react to override props?如何让 HOC 对覆盖道具做出反应?
【发布时间】:2021-08-10 20:18:04
【问题描述】:

我在 HOC 上的道具似乎并没有压倒一切。我觉得这可能是我正在使用的符号。这是我现在拥有的。

export const HOCComponent = ({ someProp }) => (
  <ContainerComponent
    propOne={someValueOne}
    propTwo={someValueTwo}
    propThree={someValueThree)
  />
);

export const wrapperComponent = props =>(
  <HOCComponent {...props} propThree={someValueFour}/>
);

someValueFour 似乎没有覆盖someValueThree。任何建议都会非常有帮助!谢谢。

【问题讨论】:

  • 我有点困惑这是否是一个 HoC 组件。通常你会使用像HoC(Component)这样的HoC组件。

标签: javascript reactjs higher-order-components


【解决方案1】:

交换传递的道具的顺序,这样你以后传递的任何东西都会覆盖之前传递的任何东西。

export const wrapperComponent = props =>(
  <HOCComponent propThree={someValueFour} {...props} />
);

HOCComponent 包装器组件还需要将所有道具传递给它所包装的组件。

export const HOCComponent = (props) => (
  <ContainerComponent
    propOne={someValueOne}
    propTwo={someValueTwo}
    propThree={someValueThree}
    {...props}
  />
);

只是关于术语的次要点,您的代码 sn-p 中没有任何内容是高阶组件。 HOC 使用一个 React 组件并返回一个新的 React 组件。

一个例子:

const withMyHOC = WrappedComponent => props => {
  // any HOC logic
  return (
    <Wrapper
      // <-- any wrapper props
    >
      <WrappedComponent
        {...props} // <-- pass props through
        // <-- override any props
      />
    </Wrapper>
  );
};

用法:

export default withMyHOC(SomeComponent);

【讨论】:

  • 答案的第二部分是我需要的。感谢您解释 HOC。我的 containerComponent 是一个 HOC,但我想它确实算在内。
【解决方案2】:

我看到你没有将道具从 HOCComponent 传递到 ContainerComponent 所以 propThree 没有被覆盖。您需要将someProp 传递给ContainerComponent

<ContainerComponent propOne propTwo propThree {...someProp} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多