(React) React配置Mobx&装饰器, Babel7

因为网上大多都是基于Babel6的,可是最近生成的新项目都是Babel7,试了网上一些方法都不行,只能靠自己了。。。所以爬完坑的总结如下:

链接地址:https://cn.mobx.js.org/best/decorators.html

(React) React配置Mobx&装饰器, Babel7_第1张图片

一、项目配置

1.生成React项目:

create-react-app demo

 

2.使用eject命令

cd demo

yarn run eject

 

3.安装mobx mobx-react

yarn add mobx mobx-react

 

4.安装babel-plugin-transform-decorators-legacy

yarn add babel-plugin-transform-decorators-legacy -D

 

5.修改配置文件,在package.json babel中加入红色字即可:

"babel": {

"plugins": [

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

],

"presets": [

"react-app"

]

}

 

 

二、项目测试

1.src/index.js下新增Provider

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'mobx-react';

ReactDOM.render(, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

 

2.新增Test类

import { observer } from 'mobx-react';
import { observable, action } from 'mobx';

class Test {
  @observable name = 'chenzhe'

  @action
  setName = () => {
    this.name = "haohaizi"
  }
}

export default Test

 

3.新增Banner组件

import React from 'react';
import Test from './Test';
import { observer } from 'mobx-react';

@observer
class Banner extends React.Component {

  constructor () {
    super();
    this.test = new Test();
    setTimeout(() => {
      this.test.setName();
    }, 1000);
  }

  render () {
    const { test } = this;
    return (
      

{test.name}

) } } export default Banner

 

4.修改App.js文件

import React from 'react';
import './App.css';
import Banner from './Banner';

function App() {
  return (
    
  );
}

export default App;

 

三、运行

在项目根目录下运行yarn start,显示chenzhe后,一秒后显示haohaizi

你可能感兴趣的:(React)