简体   繁体   English

如何让 HOC 对覆盖道具做出反应?

[英]How to get HOC in react to override props?

My props on an HOC do not seem to be overriding.我在 HOC 上的道具似乎并没有压倒一切。 I feel as though it might be the notation I'm using.我觉得这可能是我正在使用的符号。 Here is what I have right now.这是我现在所拥有的。

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

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

someValueFour does not seem to override someValueThree . someValueFour似乎没有覆盖someValueThree Any suggestions would be super helpful.任何建议都会非常有帮助。 Thank you.谢谢你。

Swap the order of the passed props such that anything you pass later overrides anything passed previously.交换传递的道具的顺序,这样你以后传递的任何东西都会覆盖之前传递的任何东西。

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

The HOCComponent wrapper component needs to also pass along all props to the component it's wrapping. HOCComponent包装器组件还需要将所有道具传递给它所包装的组件。

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

Just a minor point about terminology, nothing in your code snippet is a Higher Order Component.关于术语的问题,您的代码片段中没有任何内容是高阶组件。 HOCs consume a React component and return a new React Component. HOC 使用一个 React 组件并返回一个新的 React 组件。

An Example:一个例子:

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

usage:用法:

export default withMyHOC(SomeComponent);

I saw you don't pass props from HOCComponent to ContainerComponent so propThree is not override.我看到你没有将道具从HOCComponent传递给ContainerComponent所以propThree没有被覆盖。 You need to pass someProp to ContainerComponent :您需要将someProp传递给ContainerComponent

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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