打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
React Native 模拟 Mobx

前言

看过 「React Native 使用 Mobx」 这篇博客的同学, 对 Mobx 应该有了一个简单直观的认识.

其实, 我们完全可以使用 RN 中的 State 来达到同样的效果.

今天的主要内容是使用 State 来模拟 Mobx, 也算是对 Mobx 的进一步认识.

如果你没有看过 React Native 使用 Mobx」, 可以下面的 「阅读原文」中获取.

效果

实现效果和 「React Native 使用 Mobx」 中的效果一致, 只是代码没有使用 Mobx 框架.

实现

LegacyCounter.js

Add 和 Minus 两个按钮分别触发各自的回调, 来更新 state.
使用 state 的变化来到达更新 View (计数的 Text 会相应的做出变化)的目的.

/** * 模拟 Mobx 在 ReactNative 上的一个小例子. * * state -> view */'use strict';import React, { Component } from 'react';import {  StyleSheet,  View,  Text,  TouchableHighlight} from 'react-native';class LegacyCounter extends Component {    //构造方法    constructor(props) {        super(props);        this.state = {            //计数            counter: 0        };    }    render () {        return (          <View style = {styles.container}>            {/*加一*/}            <TouchableHighlight                onPress = {() => {this.setState({                    counter: this.state.counter                })}}>                <Text>Add</Text>            </TouchableHighlight>            {/* 显示处理结果 */}            <Text style = {styles.resultTxtStyle}>            {this.state.counter}            </Text>            {/*减一*/}            <TouchableHighlight                onPress = {() => {this.setState({                    counter: --this.state.counter                })}}>                <Text>Minus</Text>            </TouchableHighlight>          </View>        );    }}export default class LegacyComponent extends Component {    render () {        return (            <View style = {{flex: 1, marginTop: 64}}>                <LegacyCounter/>            </View>        );    }}/* 样式定义 */const styles = StyleSheet.create({    container: {        flexDirection: 'row',        justifyContent: 'space-around'    },    resultTxtStyle: {        fontSize: 22,        color: 'red'    }});

index.ios.js

这个文件很简单, 只是调用 LegacyCounter 中的组件.

import React, { Component } from 'react';//引入自定义模块import LegacyComponent from './js/Mobx/LegacyCounter'import {  AppRegistry} from 'react-native';class RNMobxDemo extends Component {    render() {        return(            <LegacyComponent/>        );    }}AppRegistry.registerComponent('RNMobxDemo', () => MZRNTutorial);

后记

如果你想了解更多关于 RN 中 State 的知识, 请移步 State.

后续会给大家带来更多关于 RN 这些方面的东西.


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
深入浅出 React Native:使用 JavaScript 构建原生应用(上)
用JavaScript搭建高性能App—React Native实战教程
React Native:使用 JavaScript 构建应用 | 前端头条
React Navtive框架教程 | 开发技术前线
FB开源React Native,用JS开发原生iOS应用
React Native之触摸事件(Touchable系列和onLongPress)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服