高阶组件(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 { }
我们可以在里面修改一下声明周期函数,渲染逻辑等