定义:高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件

使用高阶组件(HOC)解决交叉问题

假设有两个组件,CommentList组件从外部数据源订阅数据并渲染评论列表,BlogPost组件是一个订阅单个博客文章的组件,该组件遵循类似的模式,即在componentDidMount中添加事件处理函数订阅数据,在componentWillUnmount中清除事件处理函数,两个组件的事件处理函数内容相同。两个组件的区别在于:从数据源订阅的数据不同,并且渲染格式不同。(代码见React官网)
由此,可以将两个组件中相同的逻辑部分提取到一个高阶组件,该高阶组件能够创建类似 CommonList 和 BlogPost 从数据源订阅数据的组件 。该组件接受一个子组件作为其中的一个参数,并从数据源订阅数据作为props属性传入子组件。该高阶组件命名为WithSubscription。

import DataSource from '../DataSource'
let withSubscription = (WrappedComponent, selectData) => {
    // ……返回另一个新组件……
    return class extends React.Component {
        constructor(props) {
            super(props);
            this.handleChange = this.handleChange.bind(this);
            this.state = {
                data: selectData(DataSource, props)
            };
        }

        componentDidMount() {
            // ……注意订阅数据……
            DataSource.addChangeListener(this.handleChange);
        }

        componentWillUnmount() {
            DataSource.removeChangeListener(this.handleChange);
        }

        handleChange() {
            this.setState({
                data: selectData(DataSource, this.props)
            });
        }
        render() {
            // ……使用最新的数据渲染组件
            // 注意此处将已有的props属性传递给原组件
            const style = {
                'marginBottom':'30px'
            }
            return(
                <div style={style}>
                    <div>This is a HOC Component...</div>
                    <WrappedComponent data={this.state.data} {...this.props} />
                </div>
            );
        }
    };
}
export default withSubscription;

高阶组件使用

./pages/index.js
import React from 'react'
import HOCList from '../components/HOCList';
import CommentList from '../components/CommentList';
import BlogPost from '../components/BlogPost';
import withSubscription from '../components/WithSubscription/index'

const CommentListWithSubscription = withSubscription(
    CommentList,
    (DataSource) => DataSource.getComments()
);

const BlogPostWithSubscription = withSubscription(
    BlogPost,
    (DataSource, props) => DataSource.getBlogPost(props.id)
);
export default class extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
    }

    render() {
        const style = {
            width:'100%',
            'text-align': 'center',
            title:{
                color:'red'
            }
        }
        return (
            <div style={style}>
                <h1 style={style.title}>hello hoc</h1>
                <CommentListWithSubscription />
                <BlogPostWithSubscription />
            </div>
        );
    }
}

官网的示例代码不完全,为了更好地看到运行结果,对代码做一些修改:

  • 另外创建数据源DataSource:
./components/DataSource.js
let DataSource = {
    getComments: () => {
        return [
            'comment1', 'comment2', 'comment3'
        ]
    },
    getBlogPost: () => {
        return 'BlogPost Contents';
    },
    addChangeListener: () => { console.log('addChangeListener') },
    removeChangeListener: () => { console.log('removeChangeListener') },
}
export default DataSource;
  • 两个被包裹组件只负责对数据源的展示:
//.components/BlogPost/index.js
import React from 'react'
import { Input,Button } from 'antd'

const { TextArea } = Input;
export default class extends React.Component {
  render() {
      return (
          <div>
              <TextArea value={this.props.data} />
          </div>
      );
  }
}
//.components/BlogPCommentListst/index.js
import React from 'react'

export default class extends React.Component {
    render() {
        return (
            <div>
                {this.props.data.map((value) => (
                    <div comment={value} key={value} >{value}</div>
                ))}
            </div>
        );
    }
}

运行结果:http://localhost:3000/
React HOC-LMLPHP

完整源码地址:https://github.com/wuhuaranran/myHOC

11-16 06:05