react之高阶组件(二)

高阶组件的使用

接上文————

一、像函数一样直接调用

 1 import React, { Component } from 'react'
 2 import A from './A'
 3 
 4 class C extends Component {
 5     render() {
 6         return (
 7             <div>
 8                 <div className="title">组件C</div>
 9             </div>
10         )
11     }
12 }
13 
14 export default A(C)

二、使用修饰器

前期需要下载依赖

首先运行 npm run eject

将webpack的配置项暴露出来

安装相关插件

npm install babel-preset-stage-2 --save-dev

npm install babel-preset-react-native-stage-0 --save-dev

之后在package.json中配置babel

 1 "babel": {
 2     "presets": [
 3       "react-app"
 4     ],
 5     "plugins": [
 6       [
 7         "@babel/plugin-proposal-decorators",
 8         {
 9           "legacy": true
10         }
11       ]
12     ]
13   },

之后在组件中直接使用

 1 import React, { Component } from 'react'
 2 import A from './A'
 3 
 4 @A
 5 class B extends Component {
 6     render() {
 7         return (
 8             <div>
 9                 <div className="title">组件B</div>
10             </div>
11         )
12     }
13 }
14 
15 export default B
原文地址:https://www.cnblogs.com/dropInInt/p/12028019.html