React 高阶组件(Higher-Order Components)

概念:所谓的高阶组件就是声明一个方法,这个方法接收一个组件等作为参数,然后返回一个新组件,这就是所谓的高阶组件。

使用场景:   当有很多组件具有相似的操作的时候,这个时候,我们就可以将这些相似的操作抽取出来,以后当我们有组件需要进行这些操作的时候,就将这个组件传给这个函数,然后返回一个高阶组件,返回的高阶组件就拥有我们需要的操做了。例如

function 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() {
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
}

注意事项:    

  1. 不要去修改传进来的组件

猜你喜欢

转载自blog.csdn.net/Her_smile/article/details/81408908