React的高阶组件详解
- 
接受一个或多个函数作为参数; 返回一个新的函数; 
 2 使用场景(页面权限, 某些页面是必须用户登录成功才能进行进入;如果用户没有登录成功,那么直接跳转到登录页面;)// 定义一个高阶组件, 用于鉴权的操作 
 function loginAuth(WrapperCpn) {
 return props => {
 // 从本地存储中获取token, token有值表示已登录, 没有值表示未登录
 const token = localStorage.getItem("token")
 if(token) {
 return <WrapperCpn {...props}/>
 } else {
 return请先登录, 再跳转到对应的页面中
 }
 }
 }
const Cart = loginAuth(function() {
return 
购物车页面
})
export class App extends PureComponent {
render() {
return (
)
}
}
3 使用场景( props增强)
// 定义一个高阶组件, 对传入的组件进行props增强
function enhancedProps(WrapperCpn) {
class NewComponent extends PureComponent {
constructor() {
super()
  this.state = {
    userInfo: {
      name: "chenyq",
      age: 18
    }
  }
}
render() {
  // 如果组件本身也有传递参数, 也需要将参数添加进来
  return <WrapperCpn {...this.props} {...this.state.userInfo}/>
}
}
return NewComponent
}
// 调用高阶组件, 对组件进行props增强
const Home = enhancedProps(function(props) {
return 
{props.name}-{props.age}
})
const About = enhancedProps(function(props) {
return
{props.name}-{props.age}-{props.names}
})
export class App extends PureComponent {
render() {
return (
{/* 展示增强后的组件 /}
{/
<About names={["aaa", "bbb", "ccc"]}/>
)
}
}
参考文献: https://blog.csdn.net/m0_71485750/article/details/126694889
 
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号