高阶组件
高阶组件就是把一个组件传入返回另外一个组件,另外一个组件包裹着传入的组件
高阶函数demo
function hello() {
console.log('hello lmh');
}
function WrapperHello(fn) {
return function() {
console.log('before say hello')
fn()
console.log('after say hello')
}
}
hello = WrapperHello(hello)
hello()
react中高阶组件demo
// 属性代理
function WrapperHello(Comp) {
class WrapComp extends React.Component {
render() {
return (
<div>
<p>这是HOC高阶组件特有的元素</p>
<Comp {...this.props}></Comp>
</div>
)
}
}
return WrapComp
}
@WrapperHello
class Hello extends React.Component {
render() {
return <h2>Hello lmh</h2>
}
}
// @WrapperHello是下面语句的简写
// Hello = WrapperHello(Hello)
高阶组件有两种功能的组件:属性代理、反向继承,上面的例子为属性代理
// 改写上面的WrapperHello函数
function WrapperHello(Comp) {
// 反向继承Comp, 由此重写Comp组件的生命周期及render
class WrapComp extends Comp{
componentDidMount(){
console.log('高阶组件新增的生命周期,加载完成')
}
render() {
return <Comp></Comp>
}
}