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的文件)
安裝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;