问题导向
高阶组件是什么?有什么用?
如果你都有了答案,可以忽略本文章,或去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>
);
}
}
学习更多