初识React(7):高阶组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hope93/article/details/82421023

什么是高阶组件

高阶组件,听着好像很高大尚,但是其实高阶组件就是一个函数的参数是组件,返回的是一个新的组件。那么,高阶组件有什么好处呢,高阶组件可以减少代码冗余,把共有的代码提取出来,下面有个例子说明下:

import React from 'react'

function NewHigher(ComponentTest){
  class NewComponent extends React.Component {
    constructor() {
      super();
      this.state = {
          content: '我是内容'
      }
   }

    render() {
      return (
        <div>
           <h2>高阶组件</h2>
           <ComponentTest content={this.state.content}/>
        </div>
      )
    }
  }

  return NewComponent

}

export default NewHigher;

NewHigher返回的就是高阶组件

import React from 'react';
import NewHigher from './higherComponent.js'

class Test extends React.Component {
  render() {
    return (
      <div>
        <div>测试组件</div>
        <div>{this.props.content}</div>
      </div>
    )
  }
}

export default NewHigher(Test);

高阶组件可以这么理解吧,就是给现有组件设置一个父级,父级有的东西,现有组件都继承了,所以我们可以把所有共有的东西放在这个高阶组件中。在上面那个例子中,NewHigher就是父级,Test继承了父级中的所有东西。

猜你喜欢

转载自blog.csdn.net/hope93/article/details/82421023