介绍
小编给大家分享一下反应中高阶组件如何使用,希望大家阅读完这篇文章后大所收获、下面让我们一起去探讨吧!
<强>高阶组件强>
<李> 的不是反应的标准API。
李> <李> 的是一个函数。
李> <李> 的返回一个组件代码> <代码>。
李>
示例:
const EnhancedComponent=higherOrderComponent (WrappedComponent);
使用场景
代码复用
类似反应0.15版本之前的mixin。
多个组件同用一段代码,或者同样的方法时,可以使用的。
示例:
进口反应,{PureComponent} & # 39;反应# 39;;
const常见=(WrapComponent)=比;{
回报(
& lt; div>
& lt; h2> Title
& lt; WrapComponent/比;
& lt;/div>
);
};
const头=()=比;& lt; div> Header
;
const页脚=()=比;& lt; div> Footer
;
出口的默认类扩展PureComponent {
呈现(){
回报(
& lt; div>
& lt; div>
& lt; p>头Component
{常见(头)}
& lt;/div>
& lt;人力资源/比;
& lt; div>
& lt; p>页脚Component
{常见(页脚)}
& lt;/div>
& lt;/div>
);
}
} 在线示例
<强>抽象的状态和更改道具强>
可以通过WrappedComponent包裹的组件公共国家抽象出来。
可以通过WrappedComponent包裹的组件传递修改,添加等的道具。
示例:
const HOComp=(WrappedComponent)=比;{
返回类扩展的反应。组件{
构造函数(道具){
超级(道具);
这一点。状态={名称:& # 39;& # 39;};
}
componentDidMount () {
这一点。设置状态({name: WrappedComponent。displayName | | WrappedComponent.name | | & # 39;组件# 39;;});
}
返回& lt; WrappedComponent name={this.state.name} {…this.props}/比;
}
}
渲然劫持
条件渲然。根据道具或者状态条件返回在渲然的内容。
示例:
const HOComp=(WrappedComponent)=比;{
返回类增强器扩展WrappedComponent {
呈现(){
如果(this.props.loggedIn) {
返回super.render ()
其他}{
返回null
}
}
}
}
反向继承
返回的高阶组件类(增强)继承了WrappedComponent。
示例:
const EnchanceComponent=(WrappedCompopnent)=比;{
返回类扩展WrappedCompopnent {
构造函数(道具){
超级(道具);
这一点。状态={错误:& # 39;& # 39;};
}
componentDidMount () {/* */super.componentDidMount ();
}
呈现(){
如果(this.state.error) {
返回& lt; p> {this.state.error} & lt;/p>;
其他}{
返回super.render ();
}
}
}
};
看完了这篇文章,相信你对反应中高阶组件如何使用有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!