使用 MobX 开发 React Native 应用
来源:互联网 发布:淘宝运费险如何设置 编辑:程序博客网 时间:2024/05/17 01:10
本文将 MobX 与 React Native 结合,编写一个简单的列表客户端。这是学习使用 MobX 和 React Native 的一个不错的起点。
查看最终的代码库,点击这里。
MobX 是一款精准的状态管理工具库,对我来说非常容易学习和接受。我在 React 和 React Native 应用中使用过 Flux、Alt、Redux 和 Reflux,但我会毫不犹豫地说,MobX 的简单性立即成为了我最喜欢的状态管理工具。我期望能将它运用在未来的项目中,并且对 MobX 的发展拭目以待。
我们要开发的客户端有两个主要的组件,一个是创建新的列表,一个是向列表中加入新的条目。
首先,我们先要创建一个 React Native 应用:
react-native init ReactNativeMobX
接下来,我们进入目录下,并安装需要的依赖:mobx 和mobx-react。
npm i mobx mobx-react --save
我们也要安装一些 babel 插件,以支持 ES7 的 decorator 特性:
npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev
现在,创建一个 .babelrc 文件配置 babel 插件:
{ 'presets': ['react-native'], 'plugins': ['transform-decorators-legacy']}
因为我们编写的是一个自定义 .babelrc 文件,所有只需要 react-native 的 preset。配置 react-native 的 preset,还有指定一些先期运行的插件(我们这里是 transform-decorators-legacy 插件)。
现在,我们的项目配置好了,开始写代码。
在根目录,创建一个叫做 app 的目录。在 app 里面创建一个叫做 mobx 的目录,在 mobx 里创建一个叫做 listStore.js 的文件:
import {observable} from 'mobx'let index = 0class ObservableListStore { @observable list = [] addListItem (item) { this.list.push({ name: item, items: [], index }) index++ } removeListItem (item) { this.list = this.list.filter((l) => { return l.index !== item.index }) } addItem(item, name) { this.list.forEach((l) => { if (l.index === item.index) { l.items.push(name) } }) }}const observableListStore = new ObservableListStore()export default observableListStore
- 从 mobx 导入 observable – observable 可以给存在的数据结构如对象、数组和类增加可观察的能力。简单地给类属性增加一个@observable 装饰器(下一代 ECMAScript),或者调用 observable 或 extendObservable 函数(ES5);
- 创建一个叫做 ObservableListStore 的类;
- 创建一个可观察的数组 list;
- 创建三个操作列表数组的方法;
- 创建一个 ObservableListStore 的实例 observableListStore;
- 导出 observableListStore
现在已经用了存储器,我们修改项目的入口文件,使用存储,创建导航。如果你开发是 Android 项目,入口文件是 index.Android.js,如果是iOS 项目,则是 index.iOS.js。
import React, { Component } from 'react'import App from './app/App'import ListStore from './app/mobx/listStore'import { AppRegistry, Navigator} from 'react-native'class ReactNativeMobX extends Component { renderScene (route, navigator) { return <route.component {...route.passProps} navigator={navigator} /> } configureScene (route, routeStack) { if (route.type === 'Modal') { return Navigator.SceneConfigs.FloatFromBottom } return Navigator.SceneConfigs.PushFromRight } render () { return ( <Navigator configureScene={this.configureScene.bind(this)} renderScene={this.renderScene.bind(this)} initialRoute={{ component: App, passProps: { store: ListStore } }} /> ) }}AppRegistry.registerComponent('ReactNativeMobX', () => ReactNativeMobX)
在入口文件中我们创建了一个基本的导航状态,并导入了新创建的数组存储器。在 initialRoute 中我们传入数据存储作为属性。我们还把已经创建的组件App 作为初始路由。App 将会访问属性中的数据存储。
在 configureScene 中,我们检查类型(type)是否是 ‘Modal’,是则返回 floatFromBottom 这个场景配置项,可以把下一个场景也设置为模态的。
现在,我们来创建应用组件。这确是一个大型的组件,还有很多需要完善的地方,但我们创建了一个允许增加和删除列表条目的基本用户界面。调用数据存储的方法来和我们的应用状态交互。app/App.js 的内容:
import React, { Component } from 'react'import { View, Text, TextInput, TouchableHighlight, StyleSheet } from 'react-native'import {observer} from 'mobx-react/native'import NewItem from './NewItem'@observerclass TodoList extends Component { constructor () { super() this.state = { text: '', showInput: false } } toggleInput () { this.setState({ showInput: !this.state.showInput }) } addListItem () { this.props.store.addListItem(this.state.text) this.setState({ text: '', showInput: !this.state.showInput }) } removeListItem (item) { this.props.store.removeListItem(item) } updateText (text) { this.setState({text}) } addItemToList (item) { this.props.navigator.push({ component: NewItem, type: 'Modal', passProps: { item, store: this.props.store } }) } render() { const { showInput } = this.state const { list } = this.props.store return ( <View style={{flex:1}}> <View style={styles.heading}> <Text style={styles.headingText}>My List App</Text> </View> {!list.length ? <NoList /> : null} <View style={{flex:1}}> {list.map((l, i) => { return <View key={i} style={styles.itemContainer}> <Text style={styles.item} onPress={this.addItemToList.bind(this, l)}>{l.name.toUpperCase()}</Text> <Text style={styles.deleteItem} onPress={this.removeListItem.bind(this, l)}>Remove</Text> </View> })} </View> <TouchableHighlight underlayColor='transparent' onPress={ this.state.text === '' ? this.toggleInput.bind(this) : this.addListItem.bind(this, this.state.text) } style={styles.button}> <Text style={styles.buttonText}> {this.state.text === '' && '+ New List'} {this.state.text !== '' && '+ Add New List Item'} </Text> </TouchableHighlight> {showInput && <TextInput style={styles.input} onChangeText={(text) => this.updateText(text)} />} </View> ); }}const NoList = () => ( <View style={styles.noList}> <Text style={styles.noListText}>No List, Add List To Get Started</Text> </View>)const styles = StyleSheet.create({ itemContainer: { borderBottomWidth: 1, borderBottomColor: '#ededed', flexDirection: 'row' }, item: { color: '#156e9a', fontSize: 18, flex: 3, padding: 20 }, deleteItem: { flex: 1, padding: 20, color: '#a3a3a3', fontWeight: 'bold', marginTop: 3 }, button: { height: 70, justifyContent: 'center', alignItems: 'center', borderTopWidth: 1, borderTopColor: '#156e9a' }, buttonText: { color: '#156e9a', fontWeight: 'bold' }, heading: { height: 80, justifyContent: 'center', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#156e9a' }, headingText: { color: '#156e9a', fontWeight: 'bold' }, input: { height: 70, backgroundColor: '#f2f2f2', padding: 20, color: '#156e9a' }, noList: { flex: 1, justifyContent: 'center', alignItems: 'center' }, noListText: { fontSize: 22, color: '#156e9a' },})export default TodoList
我来解释此文件中可能不明确的地方。如果你有什么还不明白的,请留言,我会更新和回复。
- 从 mobx-react/native 导入 observer;
- 使用 @observer 装饰器描述类,确保相关数组变化后组件独立地重渲染;
- 导入已经创建好的组件 NewItem。这是我们要增加新条目时转向的组件;
- 在 addListItem中,把 this.state.text 传入 this.props.store.addListItem。在与输入框绑定的 updateText 中会更新 this.state.text;
- 在 removeListItem 中调用 this.props.store.removeListItem 并传入条目;
- 在 addItemToList 中调用 this.props.navigator.push,传入条目和数组存储两个参数;
- 在 render 方法中,通过属性解构数据存储:
const { list } = this.props.store
- 在 render 方法中,也创建了界面,并绑定了类的方法
最后,创建 NewItem 组件:
import React, { Component } from 'react'import { View, Text, StyleSheet, TextInput, TouchableHighlight } from 'react-native'class NewItem extends Component { constructor (props) { super(props) this.state = { newItem: '' } } addItem () { if (this.state.newItem === '') return this.props.store.addItem(this.props.item, this.state.newItem) this.setState({ newItem: '' }) } updateNewItem (text) { this.setState({ newItem: text }) } render () { const { item } = this.props return ( <View style={{flex: 1}}> <View style={styles.heading}> <Text style={styles.headingText}>{item.name}</Text> <Text onPress={this.props.navigator.pop} style={styles.closeButton}>×</Text> </View> {!item.items.length && <NoItems />} {item.items.length ? <Items items={item.items} /> : <View />} <View style={{flexDirection: 'row'}}> <TextInput value={this.state.newItem} onChangeText={(text) => this.updateNewItem(text)} style={styles.input} /> <TouchableHighlight onPress={this.addItem.bind(this)} style={styles.button}> <Text>Add</Text> </TouchableHighlight> </View> </View> ) }}const NoItems = () => ( <View style={styles.noItem}> <Text style={styles.noItemText}>No Items, Add Items To Get Started</Text> </View>)const Items = ({items}) => ( <View style={{flex: 1, paddingTop: 10}}> {items.map((item, i) => { return <Text style={styles.item} key={i}>• {item}</Text> }) } </View>)const styles = StyleSheet.create({ heading: { height: 80, justifyContent: 'center', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#156e9a' }, headingText: { color: '#156e9a', fontWeight: 'bold' }, input: { height: 70, backgroundColor: '#ededed', padding: 20, flex: 1 }, button: { width: 70, height: 70, justifyContent: 'center', alignItems: 'center', borderTopWidth: 1, borderColor: '#ededed' }, closeButton: { position: 'absolute', right: 17, top: 18, fontSize: 36 }, noItem: { flex: 1, justifyContent: 'center', alignItems: 'center' }, noItemText: { fontSize: 22, color: '#156e9a' }, item: { color: '#156e9a', padding: 10, fontSize: 20, paddingLeft: 20 }})export default NewItem
如果你对 React 或 React Native 熟悉,上面就没什么特别的。基本上就是访问条目的属性,遍历条目的数组,判断是否以及存在。存在则显示一条消息。
组件中我们与数据存储的唯一一处位置就是 addItem,向 this.props.store.addItem 传入了 this.props.item 和 this.state.newItem。
就这么多!
查看最终的代码库,点击这里。
- 使用 MobX 集成React Native 应用开发
- 使用 MobX 开发 React Native 应用
- MobX 在 React Native开发中的应用
- React Native使用Mobx总结
- React Native -- mobx
- React Mobx使用基础
- React Native开发android应用
- [React Native混合开发]React Native for iOS之应用
- react-native + as <react-native嵌入原生应用开发>
- 一起学react native(4) Mobx实现简单购物车
- MobX与React Native中shouldComponentUpdate的关系
- 用React-Native+Mobx做一个迷你水果商城APP
- 用React-Native+Mobx做一个迷你水果商城APP
- 【React Native开发】- React Navigation的使用
- React Native开发的通讯录应用
- React Native使用初探 --------- OpenGL应用
- React-Native开发总结-react-navigation应用与实践
- React Native开发之按钮的使用
- java集合框架、集合操作--线性表
- Android之Windows下搭建React Native Android开发环境
- call 和 apply的作用
- 网络攻防技术与实践笔记-信息收集技术手段
- 网络编程代码重用的一点问题与技巧
- 使用 MobX 开发 React Native 应用
- 7个原因:为什么要选择ArangoDB-原生多模型数据库?
- Makefile中的wildcard用法
- 并发队列-无界阻塞队列LinkedBlockingQueue原理探究
- Python3学习笔记-基本数据类型
- 五个唯独
- 机器学习实战-利用AdaBoost元算法提高分类性能
- 一键式弹出菜单
- 手写一个生产者--消费者模型例子