- with 开头是 class的高阶组件命名规范
- use 开头是 hooks的命名规范
- 都是操作函数
- 高阶组件案例
- react-redux
- react-router
- 高阶组件很简单,就是函数传入的参数是个组件
- 返回值也是一个组件
const hoc = higherOrder(wrappedComponent)const EnhancedComponent = higherOrderComponent(WrappedComponent)
HOC
- HOC就是返回值是组件的函数
- 通过组件嵌套的方式,赋予组件更多的功能
- 高阶组件文档 https://zh-hans.reactjs.org/docs/higher-order-components.html
- 本质就是 AOP,面向切片编程
高阶组件的好处
- 抽取重复代码,实现组件复用
- 条件渲染,控制组件的渲染逻辑,渲染劫持
- 捕获、劫持被处理组件的生命周期
高阶组件模板
import React from 'react'function withAddToCart (ChildComponent: React.ComponentType) {// return class组件return class extends React.Component {}// return hooksreturn props => {return <ChildComponent {...props}/>}}
购物车高阶组件
withAddToCart
import React from 'react'function withAddToCart (ChildComponent: React.ComponentType) {// return class组件return class extends React.Component {}return (props) => {const setState = useContext(appSetStateContext)const addToCart = (id, name) => {if (setState) {setState((state) => {return {...state,shoppingCart: {items: [...state.shoppingCart.items, { id, name }],},};});}}return <ChildComponent {...props} addToCart={addToCart} />};}export default withAddToCart
useAddToCart
import React, { useContext } from 'react'import {SetStateContext} from './context.js'function useAddToCart (ChildComponent: React.ComponentType) {const setState = useContext(SetStateContext)return function addToCart({id, name, desc}) {if (!setState) returnsetState(state => {return {...state,shoppingCart: {items: [...state.shoppingCart.items,{id, name, desc}]}}})}}export default useAddToCart
