react 高阶组件
- 缘起:
react 高阶组件其实是一个接收组件,return 组件的函数,说是一种组件不如说是一种机制; 学习react ,不应该只把大量的时间耗在写业务代码上,对于没有用到的高级用法自己需要学习使用来应对面试;
那么我现在就开始讲解关于react 高级组件的知识了;
首先从顶部设计开始,根据传入组件和return 组件的关系,高级组件可以分为:
- 代理模式
- 继承模式
代理形式的表达是:
function removeUserProp(WrappedComponent) {
return function newRender(props) {
const {user , ...otherProps} = props;
return <WrappedComponent {...otherProps} />
}
}
通过return 一个newRender 来封装传入的WrappedComponent 组件,事实上,返回的组件是代理了WrappedComponent组件的功能;这个是代理模式的含义;
一般的,高阶组件有下列的使用方式;
1.操作prop
2.访问ref
3.抽取状态
4.包装组件
那么对于操作prop 来说 , 我写的代码如下:
const addNewProps = (wrappedComponent , newProps) => {
return class myComponent extends wrappedComponent {
render(){
return (
<wrappedComponent {...this.props}{...newProps}/>
)
}
}
}
上述是对myComponent 组件添加newProps 数据;
访问ref 这一种方式不是推荐的使用方式, 因为它太具有灵活性;
第三种使用的方式是抽取状态,react-redux connect 函数就是抽取状态的方式 , 抽取状态模式的含义是:
傻瓜组件和容器组件的关系中,傻瓜组件不管理自己的状态,依靠容器组件进行管理,这个就是抽取模式的含义;
这里自己需要实现connect 函数和一个Provider ;
包装组件实现的方式是传入一个style 参数 作为渲染的样式。实现的代码如下:
function styleHOC(wrappedComponent , style) {
return class mycomponent extends React.component {
render(){
return (<wrappedComponent style = {style} />)
}
}
}
上面是代理形式的高阶组件 , 使用继承方式实现的高阶组件,Return 出去的组件继承传入的组件; 实现的代码如下:
function removeUserProps (wrappedComponent) {
return class myComponent extends wrappedComponent{
render(){
return super.render();
}
}
}
继承方式的高阶组件可以应用于下列场景:
操纵prop; 操纵生命周期函数;
操纵声明周期函数的代码如下:
const componentHOC = (wrappedComponent) => {
return class component extends wrappedComponent{
shouldComponentUpdate(nextProps , nextState){
if(!nextProps.isLogined) {
return;
}
}
render(){
return(
<wrappedComponent props = {this.props} />
);
}
}
}
上述是操纵生命周期函数的高阶组件的实现方式,假想的业务场景是: 用户登录成功之后才进行组件的刷新操作;
总结: react高阶组件一般的有继承方式和代理的方式,使用代理的方式(组合) , 一般来说是前人推荐的方式;以上就是react 高阶组件的相关知识点;
about me: 本科毕业一年半 , 从事web 前端开发工作 , 目前正在搭建完整的基本前端体系; 微信号: Yingbin192;欢迎交流;
欢迎关注我的公众号: