react学习:HOC高阶组件

问题导向

高阶组件是什么?有什么用?

如果你都有了答案,可以忽略本文章,或去react学习地图寻找更多答案

高阶组件

本质:是高阶函数,接收一个组件作为参数,返回一个被强化/或具有公共逻辑的组件.
作用:组件拓展与强化,公共逻辑抽离

基本使用

例子说明:

Show组件本身没有name属性,Hoc也没有传递,而是经过withName这个高阶组件强化后,它具备了name属性

第一步:声明高阶组件:让接收到的组件获取name属性
const withName = Comp => {
    const name = "高阶组件"

	props是接收组件的props
    return props => <Comp {...props} name={name} />
}

第二步:.调用高阶组件,把Show组件放到高阶组件中强化一下,并且赋值
const NewComponent = withName(Show)function Show(props) {
     age从组件传递过来,name从高阶组件获取
     return <div>{props.age}--{props.name}</div>
}

export default class Hoc extends Component {
     render() {
       return (
             <div>
               <NewComponent age={18} />
             </div>
       )
    }
}

用法二:公共逻辑抽离

const HOCFactory = (Component) => {
    class HOC extends React.Component {
    
        //此处定义多个组件的公共逻辑
        
        render(){
            retrun <Component {...this.props} />
        }
    }
    return HOC
}

装饰器写法

const withLog = Component =>{
   class NewComponent extends React.Component{
   	    componentDidMount(){
           console.log(Component.name ,'didMount', this.props)
        }
        
        render(){
           return <Component {...this.props} />;
        } 
   }
   return NewComponent
}


const withName = Component => {
   const NewComponent = (props) => {
   		return <Component {...props} name="高阶组件" />;
   };
   return NewComponent;
};
​


装饰器的高阶组件链式调用:连续赋能​,先执行withLog高阶组件,得到结果后再传递给withName高阶组件,withName的返回结果就是最终渲染结果
@withLog
@withName
class App extends Component {
   render() {
       return (
           <div>
              {this.props.age}-{this.props.name}
           </div>
      );
    }
}    

学习更多

react学习地图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值