React HOC:使用功能组件渲染劫持

时间:2018-03-21 11:30:15

标签: javascript reactjs components stateless purely-functional

this blog article开始,可以通过以下方式更改组件的呈现:

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
    }
  }
}

这似乎仅在传递的组件本身是类组件时才有效。

如何编写相同的代码以使其适用于功能组件?

1 个答案:

答案 0 :(得分:0)

我相信你可以直接将包装器中的道具传递给功能组件,如下所示:

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} />
    }
  }
}