高阶组件的定义:
参数为组件,返回值为新组件的函数;(高阶组件是一个函数)
import React, { PureComponent } from 'react'
class App extends PureComponent {
render() {
return (
<div>
App:{this.props.name}
</div>
)
}
}
function enhanceComponent(WrappedComponent){
class NewComponent extends PureComponent{
render(){
return <WrappedComponent {...this.props}/>
}
}
return NewComponent
}
const EnhanceComponent=enhanceComponent(App)
export default EnhanceComponent
高阶组件只是javascript的一个函数写法;
import React, { PureComponent } from 'react'
function enhanceRegionProps(WrappedComponent){
return props=>{
return <WrappedComponent {...props} region="中国"/>
}
}
class Home extends PureComponent{
render(){
return( <h2>Home:{`昵称:${this.props.nickname}
等级:${this.props.level}
区域:${this.props.region}`}</h2>)
}
}
class About extends PureComponent{
render(){
return <h2>About:{`昵称:${this.props.nickname} 等级:${this.props.level} 区域:${this.props.region}`}</h2>
}
}
const EnhanceHome = enhanceRegionProps(Home);
const EnhanceAbout = enhanceRegionProps(About);
class App extends PureComponent {
render() {
return (
<div>
App:
<EnhanceHome nickname="cccd" level={90}/>
<EnhanceAbout nickname="kkkk" level={99}/>
</div>
)
}
}
export default App
高阶组件实现了对组件的属性的增强