中文文档: https://cn.mobx.js.org/
使用步骤
1、安装依赖
- mobx 核心库
- mobx-react 方便在react中使用mobx技术的库
@babel/plugin-proposal-decorators 让rn项目支持es7的装饰器语法的库
yarn add mobx mobx-react @babel/plugin-proposal-decorators
2、在 babel.config.js 添加以下配置
plugins:{['@babel/plugin-proposal-decorators',{'legacy':true }}
3、新建文件 src/mobx/index.js 用来存放全局数据
```javascript import {observable,action} from “mobx”; class RootStore { // abservab1e 表示数据可监控 表示是全局数据 // 装饰器语法,增加功能 通过 Object.defineProperty 实现 @observable name=”hello”;
// action行为表示changeName是个可以修改全局共享数据的方法 @action changeName(name){ this.name=name } }
export default new Rootstore();
<a name="w9ERy"></a>### 4、在根组件中挂载> 通过Provider来挂载和传递```javascriptimport React,{Component} from 'react';import {View} from 'react-native';import rootStore from "./src/mobx";import {Provider} from "mobx-react";import Sub1 from './Sub1';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") // 注入用来获取全局数据的 到 props 上@observer // 当全局发生改变了组件的重新渲染从而显示最新的数据class Subl 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;
