高阶组件
在
React
里就有了HOC(Higher-Order Components)
的概念
高阶组件也是一个组件,但是他返回另外一个组件,产生新的组件可以对属性进行包装,甚至重写部分生命周期
const withName = (Component) => {
const NewComponent = (props) => {
return <Component {...props} name="高阶组件" />;
};
return NewComponent;
};
上面withName
组件,其实就是代理了Component
,只是多传递了一个name
参数
高阶链式调用
高阶组件还可以链式调用。
import React, { Component } from 'react'
import { Button } from 'antd'
const withName = (Component) => {
const NewComponent = (props) => {
return <Component {...props} name="高阶组件" />;
};
return NewComponent;
};
const withLog = Component=>{
class NewComponent extends React.Component{
render(){
return <Component {...this.props} />;
}
componentDidMount(){
console.log('didMount',this.props)
}
}
return NewComponent
}
class App extends Component {
render() {
return ( <div className="App"> <h2>hi,{this.props.name}</h2> <Button type="primary">Button</Button> </div> )
}
}
export default withName(withLog(App))
高阶组件装饰器写法
- 安装插件:
ES7
装饰器可用于简化高阶组件写法
npm install --save-dev babel-plugin-transform-decorators-legacy
- 在项目的根目录下,新建
config-overrides.js
cosnt { injexctBabelPlugin } = require('react-app-rewired');
module.exports = function override (config, env) {
config = injectBabelPlugin(
// 在默认的配置基础上注入
// 插件名,插件配置
["import", {
libraryName: "antd",
libraryDirectory: "es",
style: "css"
}],
config
);
config = injectBabelPlugin(
['@babel/plugin-proposal-decorators', {
"legacy": true
}],
config
)
return config;
}
- 使用装饰器
import React, { Component } from 'react'
const withName = (Component) => {
const NewComponent = (props) => {
return <Component {...props} name="高阶组件" />;
};
return NewComponent;
};
const withLog = Component=>{
class NewComponent extends React.Component{
render(){
return <Component {...this.props} />;
}
componentDidMount(){
console.log('didMount',this.props)
}
}
return NewComponent
}
@withKaikeba
@withLog
class App extends Component {
render() {
return ( <div className="App"> <h2>hi,{this.props.name}</h2>
<Button type="primary">Button</Button> </div> )
}
}
export default App