React - 高级组件的简单应用

高阶组件(HOC)是react中对组件逻辑进行重用的高级技术。但高阶组件本身并不是React API。它只是一种模式。

具体而言,高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件。

举个栗子

比如我们需要在input标签下面加上一个计时器。你可以写一个组件Time然后使用它,但是这很死板。

比如这个Time中没有“下午”,或者说它含有你不想要的其他部分,不是很灵活,但是用高级组件可以很好的解决。

function withTime(WrappedComponent) {//传入一个组件
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        date: new Date(),
      }
    }

    componentDidMount () {
      this.timeID = setInterval( () => this.tick(), 1000);
    }
    componentWillUnmount () {
      clearInterval(this.timeID);
    }
    tick () {
      this.setState({
        date: new Date()
      })
    }
    //上面都是一些内部逻辑
    render () {
      return (//返回组件,但是加上了我们的time
        <WrappedComponent time = { this.state.date } { ...this.props } />
      );

    }
  }
}

class App extends React.Component {
  constructor (props) {
      super(props);
  }

render () {
    return (
      <div>
      <input type = 'text'  ref = { n => this.input = n} />
      <div> { this.props.time.toLocaleTimeString()} </div>
      
      </div>
      //通过this.props.time调用
    );
  }
}

let App1 = withTime(App);
ReactDOM.render(
  <App1 />,
  document.getElementById("root")
)

高阶组件俩点应用

1:属性代理 (也就是说在新组件里面加上一下App里面没有的属性,额外的属性)

2:反向继承 

例如:我们写返回组件是可以写成return class extends WrappedComponent { }

我们可以在里面修改一下声明周期函数,渲染逻辑等

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值