React higher order component

#react #javascript

什么是Higher Order Component ?

HOC(Higher Order Component)主要用来封装(增强)其它组件,即一个组件封装了另外一个组件。

const MyComponent = (props) => {}
   if (props.data) {
       return (
            <h1>Waiting</h1>
       );
   }

   return <div>{props.data}</div>;
}

const Enhance = (WrappedComponent) => class extends Component {
    constructor() {
        this.state = { data: null }; 
    }

    componentDidMount() {
        this.setState({ data: "Hello"});
    }

    render() {
        return <WrappedComponent {...this.props} data={this.state.data}/>
    }
}

export default Enhance(MyComponent);

如上述代码所示,Enhance(MyComponent)就返回了一个HOC,这个返回的组件封装了MyComponent,因此,HOC可以完成以下一些常用的操作,比如: 操作props, 封装通用的样式等

操作props

例如如下代码: 判断登录用户

const WithLoginUser = (WrappedComponent) => (props) => {
    const user = getCurrentLoginUser();
    return (
        <WrappedComponent {...props} user={user}/>
    )
}

根据props内容条件渲染

const ConditionRender = (WrappedComponent) => (props) => {
    if (props.data !== null) {
        return null;
    } else {
        return <WrappedComponent {...props} />
    }
}

封装通用的样式

可以做一些通用样式的处理

const StyledComponent = (WrappedComponent) => (props) => {
    return (
        <div className="general-style">
            <WrappedComponent {...props} />
        </div>
    )
}

参考材料

  1. https://medium.com/@housecor/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc?swoff=true#.y0olcg5dt
  2. http://engineering.blogfoster.com/higher-order-components-theory-and-practice/
  3. https://facebook.github.io/react/