javascript - react HOC : render hijacking with functional components

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

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

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

最佳答案

我相信您可以像这样将包装器中的 Prop 直接传递给功能组件:

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

关于javascript - react HOC : render hijacking with functional components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49405189/

相关文章:

reactjs - 是否可以直接从其低阶组件将数据传递到 withTracker ?

reactjs - React 中的表单性能是否不佳?

javascript - Vue.js - child 组件通信

javascript - 自定义验证器不调用 Angular 2 中的每个按键

javascript - 使用 bootstrap Modal 弹出图像?

javascript - 如何使用JQuery $.when按顺序处理ajax调用?

.net - 用于 .Net 开发的多格式文件查看器

php - 启用按钮的简单javascript函数?

javascript - ReactJS 中的浏览器检测

java - 如何一次设置所有 Java Swing GUI 组件背景和前景(字体)颜色?