简体   繁体   中英

React HOC : render hijacking with functional components

From this blog article , the rendering of a component can be altered this way:

function iiHOC(WrappedComponent) {
  return class Enhancer extends WrappedComponent {
    render() {
      const elementsTree = super.render()
      let newProps = {};
      if (elementsTree && elementsTree.type === 'input') {
        newProps = {value: 'may the force be with you'}
      }
      const props = Object.assign({}, elementsTree.props, newProps)
      const newElementsTree = React.cloneElement(elementsTree, props, elementsTree.props.children)
      return newElementsTree
    }
  }
}

This seems to work only if the passed components is itself a class component.

How would one go about writing the same code so that it works on functional components ?

I believe you can just pass the props from the wrapper directly to the functional component like so:

const jediEnhancer = (FunctionalComponentToWrap) => {
  return class jediEnhancer extends React.Component {
    constructor(props){
      super(props);

      this.state = {
        forceIsWithUser: false 
      };

      this.awakenTheForce = this.awakenTheForce.bind(this);

    awakenTheForce(){
      this.setState({forceIsWithUser: true});
    }

    render(){
      return <FunctionalComponentToWrap awakenTheForce={this.awakenTheForce} {...this.props} />
    }
  }
}

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