定义:高阶组件是参数为组件,返回值为新组件的函数。
注意:高阶组件是一个函数(而不是组件),它接受一个组件作为参数,返回一个新的组件。这个新的组件会使用你传给它的组件作为子组件。
为什么要用高阶组件?
- 可操纵被包裹组件WrappedComponent的props
- 提取state,即提取公用数据
- 通过ref访问组件的实例
- 用其他元素包裹组件
1、高阶组件实现
const highComponentFun = (WrappedComponent, data) => {
return class extends React.Component {
constructor (props) {
super(props)
this.state = {
commonMessage: '我是被提取出来的公用的数据'
}
}
componentWillMount () {}
componentDidMount () {}
// 通过refs 访问 被包裹的组件的实例
handleRef = (wrappedComponentInstance) => {
console.log(wrappedComponentInstance)
}
render () {
return <div>
<div>{data.name}</div>
<WrappedComponent {...this.props}
data={this.state}
ref={this.handleRef}/>
</div>
}
}
}
2、高阶组件应用1:
class Cat1 extends React.Component {
render () {
const {data,sex} = this.props
return <div>
<div>
{data.commonMessage}
</div>
我的性别是:{sex}
</div>
}
}
const Cat = highComponentFun(Cat1,{name:'我是被包裹组件Cat'})
组件应用2:与 react-router、redux、react-redux 结合
const Dog2 = highComponentFun(Dog1,{name:'我是被包裹组件Dog'})
const mapStateToProps = (state) => {
return {
age:30
}
}
const Dog = withRouter(connect(mapStateToProps, {})(Dog2))
使用:
<Dog />
<Cat sex={'男'} />