React-使用装饰器

时间:2023-03-09 14:27:07
React-使用装饰器

  create-react-app默认不支持装饰器的,需要做以下配置。

  打开 package.json ,可以看到eject。运行 npm run eject 可以让由create-react-app创建的项目的配置项暴露出来。

{
...
"scripts": {
...
"eject": "react-scripts eject"
},
...
}

运行 npm run eject 

  此时,项目中多了一个config文件,并且各个配置文件已经暴露出来了。(运行npm run eject之前,保证本地没有待提交到git的文件)

React-使用装饰器

安装babel插件
  Babel >= 7.x

npm install --save-dev @babel/plugin-proposal-decorators

  Babel@6.x

npm install --save-dev babel-plugin-transform-decorators-legacy

修改package.json文件的babel配置项
  Babel >= 7.x

  "babel": {
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }]
],
"presets": [
"react-app"
]
}

  Babel@6.x

"babel": {
"plugins": [
"transform-decorators-legacy"
],
"presets": [
"react-app"
]
}

至此,就可以在项目中使用装饰器了

@MyContainer
class B extends Component{
render(){
return (
<p>B组件</p>
)
}
}
export default B;