官方文档:https://zh-hans.reactjs.org/docs/higher-order-components.html
组件是 React 中代码复用的基本单元。但有时会发现某些模式并不合适传统组件。
含义
HOC 是灵活使用 react 组件的一个技巧,本身不是一个组件,是一个参数为组件,返回值是一个组件的函数。
HOC 本身不是 react 中 API 的一部分,是 react 的组合特性而形成的设计模式。
作用
* 强化组件
高阶组件返回的组件,可以劫持上一层传过来的 props,然后混入新的 props,来增强组件的功能。
1.混入 props
通过承接上层的 props,在混入自己的 props,来强化组件
function classHOC(WrapComponent){
return class Idex extends React.Component{
state={
name:'gs'
}
componentDidMount(){
console.log('HOC')
}
render(){
return <WrapComponent
{ ...this.props }
{...this.state }
/>
}
}
}
function Index(props){
const { name,...otherProps } = props
useEffect(()=>{
console.log( 'index' )
},[])
return <div>my name is { name }</div>
}
export default classHOC(Index)
hooks 版本应用
function functionHoc(WrapComponent){
return function Index(props){
const [ state , setState ] = useState({ name :'gs' })
return <WrapComponent { ...props } { ...state } />
}
}
2.state 控制更新
可以将 HOC 的 state 的配合起来,控制业务组件的更新。类似用于处理来自 react-redux 中 state 更改,带来的订阅更新的作用。
function classHOC(WrapComponent){
return class Idex extends React.Component{
constructor(){
super()
this.state={
name:'gs'
}
}
const changeName=(name)=>{
this.setState({ name })
}
render(){
return
<WrapComponent
{ ...this.props }
{ ...this.state }
changeName={this.changeName}
/>
}
}
}
function Index(props){
const [ value ,setValue ] = useState(null)
const { name ,changeName } = props
return <div>
<div> hello,world , my name is { name }</div>
改变name <input onChange={ (e)=> setValue(e.target.value) } />
<button onClick={ ()=> changeName(value) } >确定</button>
</div>
}
export default classHOC(Index)
* 复用逻辑
高阶组件可以对 react 组件进行加工处理。可以根据需求对原有的组件进行加工,可以定制专属的 HOC。
官网例子:
例如,假设有一个 CommentList 组件,它订阅外部数据源,用以渲染评论列表:
class CommentList e