react高阶组件

高阶组件

为了提高组件复用性,在react中就有了HOC(Higher-Order Component)的概念。所谓的高阶组件,其本质依旧是组件,只是它返回另外一个组件,产生新的组件可以对属性进行包装,也可以重写部分生命周期。

首先看一下简单的例子:在components文件夹下新建Hoc.js组件文件,并在index.js中引入该组件。

Hoc.js

import React, { Component } from "react";

function test(props){
    return (
        <div>{props.stage} - {props.name}</div>
    )
}

const withName = Comp => {
   return props => <Comp {...props} name="高阶组件试用" />
  }

 

export default withName(test)

index.js

上面例子中的widthName组件就是一个高阶组件,接收了一个组件,为该组件传递一个name参数后,返回扩展以后的组件,这就是高阶组件的用法。

 重写生命周期

当我们需要在高阶组件的某个生命周期里面获取数据或者做其他的操作的时候,可以使用高阶组件重写生命周期。

 Hoc.js

import React, { Component } from "react";

function test(props){
    return (
        <div>{props.stage} - {props.name}</div>
    )
}

const withName = Comp => {
   class NewComponent extends Component{
        componentDidMount(){
            console.log('高阶组件重写生命周期');
        }
        render(){
            return <Comp {...this.props} name="高阶组件试用" />
        }
    }
    return NewComponent
  }

 

export default withName(test)

高阶组件链式调用

import React, { Component } from "react";

function test(props){
    return (
        <div>{props.stage} - {props.name}</div>
    )
}

const withName = Comp => {
   class NewComponent extends Component{
        componentDidMount(){
            console.log('高阶组件重写生命周期');
        }
        render(){
            return <Comp {...this.props} name="高阶组件试用" />
        }
    }
    return NewComponent
  }

const widthLog = Comp => {
    console.log(Comp.name + '渲染了');
    return props => <Comp {...props} />
}
 

export default widthLog(withName(test))

 高阶组件装饰器写法

在上面的高阶组件链式调用的时候,我们使用的嵌套的写法,这种写法很不直观,因此可以借助ES7里面的装饰器来处理这种问题。

首先,需要在项目根目录执行安装命令:

npm install --save-dev babel-plugin-transform-decorators-legacy

其次,修改config-overrides.js

然后,重启项目后改造上面的高阶组件:

1,将连个高阶组件移动到需要改造的test组件上面;

2,在需要改造的test组件前面依次调用两个高阶组件;

3,将需要改造的test组件由函数组件改为class类组件;

import React, { Component } from "react";

const withName = Comp => {
   class NewComponent extends Component{
        componentDidMount(){
            console.log('高阶组件重写生命周期');
        }
        render(){
            return <Comp {...this.props} name="高阶组件试用" />
        }
    }
    return NewComponent
  }

const withLog = Comp => {
    console.log(Comp.name + '渲染了');
    return props => <Comp {...props} />
};
 
@withName
@withLog

class test extends Component{
    render(){
        return (
            <div>{this.props.stage} - {this.props.name}</div>
        )
    }
}
export default test

 

 

posted on 2019-02-12 22:02  紅葉  阅读(733)  评论(0编辑  收藏  举报