react 使用modx

添加依赖

yarn add mobx mobx-react @babel/plugin-proposal-decorators

babel.config.js添加配置

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
        "@babel/plugin-proposal-decorators",
        {
            "legacy": true
        }
    ]
  ]
};

配置全局modx

import {observable,action,makeObservable} from 'mobx';

class RootStore{

    constructor() {
        // 使用 makeObservable mobx6.0 才会更新视图
        makeObservable(this);
      }
    @observable
    name ="page";

    @action
    changeName(name){
        this.name=name;
    }

}

export default new RootStore();

根节点使用provide包裹

import { Provider } from 'mobx-react';
import React, { Component } from 'react';
import {View,Text} from 'react-native'
import Btn from './components/btn/Btn'
import RootStore from './mobx'
class App extends Component {
  render() {
     
    return (
      <View>
        <Provider RootStore={RootStore}>
          <Btn></Btn>
        </Provider>
      </View>
    );
  }
}

export default App;

子节点使用

import React, { Component } from 'react';
import {View,Text} from 'react-native'
import {inject,observer} from 'mobx-react'
@inject("RootStore")
@observer
class Btn extends Component {
    handelClick= ()=>{
        this.props.RootStore.changeName('吴亦凡');
        alert(JSON.stringify(this.props.RootStore.name));
    }
    render() {
       
        return (
            <View>
                <Text onPress={this.handelClick}>btn:{this.props.RootStore.name}</Text>
            </View>
        );
    }
}

export default Btn;

效果图

react 使用modx

上一篇:react-mobx,react-mobx6使用案例


下一篇:严选 ELK Stack 选书指南