React高阶组件

定义:高阶组件是参数为组件,返回值为新组件的函数。

注意:高阶组件是一个函数(而不是组件),它接受一个组件作为参数,返回一个新的组件。这个新的组件会使用你传给它的组件作为子组件。

为什么要用高阶组件?

  • 可操纵被包裹组件WrappedComponent的props
  • 提取state,即提取公用数据
  • 通过ref访问组件的实例
  • 用其他元素包裹组件

1、高阶组件实现

const highComponentFun = (WrappedComponent, data) => {
  return class extends React.Component {
    constructor (props) {
      super(props)
      this.state = {
        commonMessage: '我是被提取出来的公用的数据'
      }
    }

    componentWillMount () {}

    componentDidMount () {}

    // 通过refs 访问 被包裹的组件的实例
    handleRef = (wrappedComponentInstance) => {
      console.log(wrappedComponentInstance)
    }

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

2、高阶组件应用1:

class Cat1 extends React.Component {
  render () {
    const {data,sex} = this.props
    return <div>
      <div>
        {data.commonMessage}
      </div>
      我的性别是:{sex}
    </div>
  }
}
const Cat = highComponentFun(Cat1,{name:'我是被包裹组件Cat'})

组件应用2:与 react-router、redux、react-redux 结合

const Dog2 = highComponentFun(Dog1,{name:'我是被包裹组件Dog'})
const mapStateToProps = (state) => {
  return {
    age:30
  }
}
const Dog = withRouter(connect(mapStateToProps, {})(Dog2))

使用:

<Dog />
<Cat sex={'男'} />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值