- 安装mobx
这里安装的是mobx5
npm insatall mobx --save
npm insatall mobx-react --save
- 安装插件
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}]
]
- 如果使用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 (
<View style={styles.container}>
<Text style={styles.welcome}>计数器的一个Mobx例子</Text>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-around',
marginTop: 40,
}}>
<Text>当前的值是: {this.appStore.timer}</Text>
<TouchableOpacity
onPress={() => {
this.appStore.startTimer();
}}>
<Text
style={{
backgroundColor: 'green',
color: 'white',
marginLeft: 30,
fontSize: 20,
}}>
计时
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
},
welcome: {
marginTop: 20,
fontSize: 20,
},
});