React高阶组件

高阶组件定义:
高阶组件就是一个函数,该函数接受一个组件作为参数,并返回一个新的组件
高阶组件的作用:
封装并抽离组件中的通用逻辑,让此逻辑更好的在组件中复用;

如何实现高阶组件:1、属性代理 2、反向继承
1、属性代理是最常见的实现方法,它的做法是将被处理组件的props和新组件props一起传递给新组建,从而装饰被处理组件;
举个例子:如果addOneCount方法在项目中复用率较高,如果在每个用到的组件中都实现一次,那代码就会冗余;所以我们用高阶组件实现;
高阶组件代码如下:

import React, { Component } from 'react';
export default function HOC(WrappedCompnnet) {//创建一个函数,用来返回一个新的组件
    return class Hoc extends Component {
        addOneCount(value) {
            return ++value;
        }
        render() {
            const newProps = { addOneCount: this.addOneCount };
            return (
                <WrappedCompnnet {...this.props} {...newProps} />
            )
        }
    }
}

被处理组件的代码如下:

import React, { Component } from 'react';
import HOC from './common/Hoc';

@HOC
export default class WrappedCompnnet extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 1
        }
    }
    add() {
        //这样就可以通过props来访问高阶组件里面的方法
        let value = this.props.addOneCount(this.state.count);
        this.setState({ count: value });
    }
    render() {
        return (
            <div>
                <p style={{ color: 'green' }}>{this.state.count}</p>
                <input value="++1" type="button" onClick={this.add.bind(this)} />
            </div>
        )
    }
}

// const ComputerCounters=Hoc(ComputerCounter);
// export default ComputerCounters;

如果再增加一个组件,也需要addOneCount方法处理;只需要如下:

import React, { Component } from 'react';
import HOC from './common/Hoc';
@HOC
export default class WrappedCompnnet1 extends Component {
    render() {
        const value=1;
        return (
            <div>
              {this.props.addOneCount(value)}
            </div>
        )
    }
}

属性代理实际上就是通过HOC这个函数,像被处理的组件WrappedCompnnet添加一些新增加的属性,并返回一个包含被处理组件的新组建
上述代码是使用ES7的decorator装饰器(webpack支持需要babel-plugin-transform-decorators-legacy)来实现对原组件WrappedCompnnet的装饰和增强;或者使用注释中的函数方法一样可以达到相同的效果。

第二种方法:反向继承(extends),直接看代码:
高阶组件代码:

import React, { Component } from 'react';

export default function Hoc(WrappedComponent) {
    return class Hoc extends WrappedComponent {
        constructor(props) {
            super(props);
        }
        addOneCount() {
            console.log(this.state.count);
            this.setState({ count: ++this.state.count })
        }
        render(){
           return super.render();
        }
    }
}

被处理组件:

import React,{Component} from 'react';
import InheritHoc from './common/inherit';

@InheritHoc
export default class OriginComponent extends Component{
    constructor(props){
        super(props);
        this.state={count:1}
    }

    render(){
        return(
            <div>
                <p>{this.state.count}</p>
                <input type="button"  value="++1" onClick={this.addOneCount.bind(this)} />
            </div>
        )
    }
}

新生成的Hoc组件继承了传入的WrappedComponent组件,从而Hoc组件可以获取WrappedComponent组件里的所有方法和属性,并且可以拿到该组件里面的state进行修改,从而改变组件的行为,所谓“渲染劫持”,可以说,通过反向继承方法实现的高阶组件相比于属性代理实现的高阶组件,功能更强大,个性化程度更高,适应更多的场景。
在子组件通过super.render()来渲染父组件时,父组件中的this指向的是子组件;所以可以访问到addOneCount方法;

参考文章:https://juejin.im/post/59818a485188255694568ff2
https://github.com/brickspert/blog/issues/2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在目前的前端社区,『推崇组合,不推荐继承(prefer composition than inheritance)...
    Wenliang阅读 77,717评论 16 124
  • React进阶之高阶组件 前言 本文代码浅显易懂,思想深入实用。此属于react进阶用法,如果你还不了解react...
    流动码文阅读 1,191评论 0 1
  • title: react-高阶组件date: 2018-07-11 09:42:35tags: web 组件间抽象...
    Kris_lee阅读 26,020评论 2 21
  • 高阶组件(HOC)是 React 中用于复用组件逻辑的一种高级技巧。HOC 自身不是 React API 的一部分...
    明里人阅读 619评论 0 1
  • 高阶组件是react应用中很重要的一部分,最大的特点就是重用组件逻辑。它并不是由React API定义出来的功能,...
    叫我苏轼好吗阅读 921评论 0 0