- 效果图
1. 使用步骤
-
安装依赖
mobx
核心库mobx-react
方便在react中使用mobx技术的库@babel/plugin-proposal-decorators
让RN
支持ES7
的装饰器语法的库
yarn add mobx mobx-react @babel/plugin-proposal-decorators
-
在babel.config.js添加以下配置
plugins: [
['@babel/plugin-proposal-decorators', { 'legacy': true }]
]
2. 代码示例
- 补充
子控件不能写成小写字母开头,会报错
如下会报错,因为<btn>
是小写开头
<View style={{
justifyContent: 'center',
alignItems: 'center',
flex: 1
}}>
<Provider RootStore={rootStore}>
<btn></btn>
</Provider>
</View>
- 获取数据
- 创建控件
// 子控件
import React, {Component} from 'react';
import {View, Text, Button} from 'react-native';
import {inject, observer} from 'mobx-react';
@inject("RootStore")
@observer
class IndexComp extends Component {
constructor(props) {
super(props)
this.state = {
count : 2,
names: "Han"
}
}
clickName = () => {
this.props.RootStore.changeName("八戒");
this.setState({
names : "lisi"
})
}
clickBtn = () => {
this.props.RootStore.changeAge()
this.props.RootStore.changeName("俊华");
}
render() {
return (
<View>
<Text onPress={this.clickName}>Btn: {this.state.names} ,age: {this.state.count}</Text>
<Text onPress={this.clickName}>Btn: {this.props.RootStore.name} ,age: {this.props.RootStore.age}</Text>
<Button
title={this.props.RootStore.name}
onPress={this.clickBtn}></Button>
</View>
);
}
}
export default IndexComp;
import React,{Component} from 'react';
import rootStore from './MobxCode/mobx/index'; // 导入store
import {Provider} from 'mobx-react'; // 导入Provider
import Btn from './MobxCode/components/Btn';
import {
View,
} from 'react-native';
class App extends Component {
render() {
return (
<View style={{
justifyContent: 'center',
alignItems: 'center',
flex: 1
}}>
<Provider RootStore={rootStore}>
<Btn></Btn>
</Provider>
</View>
)
}
}
export default App;
- 创建store
import {observable, action, makeObservable} from 'mobx';
class RootStore {
// 有的人这个constructor方法不写也可以,
// 但是当不会触发值改变的时候,就可以考虑把这个补充上去
constructor() {
makeObservable(this)
}
// ES7的装饰器语法 Object.defineProperty
@observable name = "张三";
@observable age = 3;
@action changeName(name){
this.name = name;
}
@action changeAge(){
this.age += 1
}
}
export default new RootStore();