1 安装依赖 yarn add mobx mobx-react @babel/plugin-proposal-decorators
2 在babel.config.js添加以下配置
plugins: [
['@babel/plugin-proposal-decorators', { 'legacy': true }]
]
3 新建mobx/index.js用来存放全局数据
import { observable, action } from "mobx";
class RootStore {
// observable 表示数据可监控 表示是全局数据
@observable name = "hello";
// action行为 表示 changeName是个可以修改全局共享数据的方法
@action changeName(name) {
this.name = name;
}
}
export default new RootStore();
4 在根组件中挂载
通过provide来挂载和传递
import React, { Component } from 'react';
import { View} from 'react-native';
import rootStore from "./mobx";
import { Provider} from "mobx-react";
class Index extends Component {
// 正常
render() {
return (
<View >
<Provider rootStore={rootStore} >
<Sub1></Sub1>
</Provider>
</View>
);
}
}
5 其他组件中使用
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import {inject,observer } from "mobx-react";
@inject("rootStore") // 注入 用来获取 全局数据的
@observer // 当全局发生改变了 组件的重新渲染 从而显示最新的数据
class Sub1 extends Component {
changeName = () => {
// 修改全局数据
this.props.rootStore.changeName(Date.now());
}
render() {
console.log(this);
return (
<View><Text onPress={this.changeName}>{this.props.rootStore.name}</Text></View>
);
}
}
export default Index;
mobx使用步骤
最新推荐文章于 2025-05-10 03:54:37 发布