RN开发系列<9>--Mobx(1)入门篇

  • 效果图
    请添加图片描述

1. 使用步骤

  1. 安装依赖

    • mobx 核心库
    • mobx-react 方便在react中使用mobx技术的库
    • @babel/plugin-proposal-decoratorsRN 支持 ES7 的装饰器语法的库
     yarn add mobx mobx-react @babel/plugin-proposal-decorators
    
  2. 在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>
  1. 获取数据
  • 创建控件
// 子控件
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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值