简述什么是React 高阶组件?

高阶组件(Higher-Order Components,简称HOC)是React中用于复用组件逻辑的一种高级技术。它不是React的API的一部分,而是一种基于React的组合特性的设计模式。

高阶组件就是一个函数,接受一个组件作为参数,并返回一个新的组件。这个新的组件会使用原始的组件,并可以在其基础上添加新的props或者新的功能。

function higherOrderComponent(WrappedComponent) {
  return class extends React.Component {
    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

在这个例子中,higherOrderComponent就是一个高阶组件。它接收一个组件WrappedComponent,返回一个新的组件。新的组件会渲染WrappedComponent,并且将自己接收的props传递给WrappedComponent

高阶组件的用途非常广泛,例如,可以用于控制props,抽象state,控制渲染等等。比如React-Redux的connect函数就是一个高阶组件,它用于将React组件连接到Redux store,使得组件可以访问store中的state和dispatch函数。

发表评论

后才能评论