react-native项目安装mobx时装饰器配置

  1. 安装mobx
    这里安装的是mobx5
npm insatall mobx --save
npm insatall mobx-react --save
  1. 安装插件
npm install babel-plugin-transform-decorators-legacy --save-dev
npm install @babel/plugin-proposal-decorators --save-dev

并在package.json中添加:

"babel": {
    "plugins":[
      ["@babel/plugin-proposal-decorators", {"legacy":true}],
      ["@babel/plugin-proposal-class-properties", {"loose":true}]
    ]
  1. 如果使用TS,注意tsconfig.json文件增加
"experimentalDecorators": true,

重新运行项目,可以正常运行了。以下为package.json中的代码:

"dependencies": {
    "mobx": "^5.5.0",
    "mobx-react": "^5.2.8",
    "mobx-state-tree": "^3.5.0",
    "react": "17.0.1",
    "react-native": "0.64.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/plugin-proposal-decorators": "^7.13.5",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@types/jest": "^26.0.20",
    "@types/react-native": "^0.64.0",
    "@types/react-test-renderer": "^16.9.2",
    "babel-jest": "^26.6.3",
    "babel-plugin-transform-decorators-legacy": "^1.3.5",
    "eslint": "^7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.64.0",
    "react-test-renderer": "17.0.1",
    "typescript": "^3.8.3"
  },
  "babel": {
    "plugins": [
      [
        "@babel/plugin-proposal-decorators",
        {
          "legacy": true
        }
      ],
      [
        "@babel/plugin-proposal-class-properties",
        {
          "loose": true
        }
      ]
    ]
  }

测试代码

import React from 'react';
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {observer} from 'mobx-react';
import {action, observable} from 'mobx';

class AppState {
  @observable timer: number = 0;

  // 重置计数器
  @action.bound
  resetTimer = () => {
    console.log('AppState resetTimer');
    this.timer = 0;
  };

  @action.bound
  startTimer = () => {
    setInterval(() => {
      this.timer = this.timer + 1;
    }, 1000);
  };
}

@observer
export default class App extends React.Component<{}, {}> {
  appStore: AppState;

  constructor(props: any) {
    super(props);
    this.appStore = new AppState();
  }

  render() {
    return (
      
        计数器的一个Mobx例子
        
          当前的值是: {this.appStore.timer}
           {
              this.appStore.startTimer();
            }}>
            
              计时
            
          
        
      
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
  },
  welcome: {
    marginTop: 20,
    fontSize: 20,
  },
});

你可能感兴趣的:(react-native项目安装mobx时装饰器配置)