高阶组件
定义:
接收一个组件 返回一个新组件
运用场景:
扩展公用组件 可对公用组件进行扩展
示例:
高阶链式组件
定义:
组件之间的多层嵌套
沿用上面一个例子
const NewHanbin = withHanbin(hanbin)
这只是一层嵌套 还可能多层嵌套
const NewHanbin = withHanbin(withHanbin(hanbin))
嵌套层数多了以后显得累赘,此时建议使用装饰器:
配置使用:
- 进行安装
cnpm install --save-dev babel-plugin-transform-decorators-legacy
- 在config-override.js中进行配置
(针对于安装了react-app-rewired 可查看上一篇文章https://blog.csdn.net/qq_40593656/article/details/103974981)
const { injectBabelPlugin } = require('react-app-rewired')
module.exports = function override (config, env) {
config = injectBabelPlugin(
['@babel/plugin-proposal-decorators', { legacy: true }],
config
)
return config
}
- 修改嵌套代码
说明:
将外层嵌套的函数放在上面
最里面最底层的组件放在下面
然后用装饰器
从最外层往里层写 写在最里层的组件上面
就比如
const NewHanbin = withHanbin(hanbin)
就相当于
@withHanbin
class Hanbin extends Component {
render () {
return (
<div>
{this.props.stage}-{this.props.name}
</div>
)
}
}
但是写在输出的组件里 从 变成
注意:
用装饰器装饰的组件必须是个class 并且不能写有export default