简体   繁体   中英

How to get HOC in react to override props?

My props on an HOC do not seem to be overriding. 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 . 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.

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.

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. You need to pass someProp to ContainerComponent :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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