React高阶组件
有时候,我们的组件中可能有很多的组件基本内容一样,只是其中某一部分不同,或者是请求地址不同,或者是组件中的处理方式不同,我们可以使用高阶组件,来进行重构,让代码看起来更加简洁高大上。
比如有以下两个组件:
//Bar.js
const Bar = (props) => (
<div>
<h1>{props.name}</h1>
</div>
)
//Foo.js
const Foo = (props) => (
<div>
<h2>{props.name}</h2>
</div>
)
可以看到,两个组件基本相同,只是一个是h1,一个是h2,当然我们只是举个例子,肯定组件也没这么简单的,会有一些自己定义的方法等等。我们可以写一个高阶组件,高阶组件就是一个方法,他的参数是一个组件,然后返回的还是一个组件,这样的就叫做高阶组件
const high = (WrapperComonent) => {
return class extends Component {
render() {
return <WrapperComponent { ...this.props }/>
}
}
}
const Bar = high((props)=>(
<h1>{ props.name }</h1>
))
const Foo = hign((props) => (
<h2>{ props.name }</h2>
))
这样就可以正常运行了,可以试试看。