使用 MobX 开发 React Native 应用 - Go语言中文社区

使用 MobX 开发 React Native 应用



本文将 MobX 与 React Native 结合,编写一个简单的列表客户端。这是学习使用 MobX 和 React Native 的一个不错的起点。

使用 MobX 开发 React Native 应用

使用 MobX 开发 React Native 应用

查看最终的代码库,点击这里

MobX 是一款精准的状态管理工具库,对我来说非常容易学习和接受。我在 React 和 React Native 应用中使用过 Flux、Alt、Redux 和 Reflux,但我会毫不犹豫地说,MobX 的简单性立即成为了我最喜欢的状态管理工具。我期望能将它运用在未来的项目中,并且对 MobX 的发展拭目以待。

我们要开发的客户端有两个主要的组件,一个是创建新的列表,一个是向列表中加入新的条目。

使用 MobX 开发 React Native 应用

首先,我们先要创建一个 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 = 0

class 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
  1. mobx 导入 observableobservable 可以给存在的数据结构如对象、数组和类增加可观察的能力。简单地给类属性增加一个 @observable 装饰器(下一代 ECMAScript),或者调用 observable extendObservable 函数(ES5);
  2. 创建一个叫做 ObservableListStore 的类;
  3. 创建一个可观察的数组 list
  4. 创建三个操作列表数组的方法;
  5. 创建一个 ObservableListStore 的实例 observableListStore
  6. 导出 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'

@observer
class 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

我来解释此文件中可能不明确的地方。如果你有什么还不明白的,请留言,我会更新和回复。

  1. mobx-react/native 导入 observer
  2. 使用 @observer 装饰器描述类,确保相关数组变化后组件独立地重渲染;
  3. 导入已经创建好的组件 NewItem。这是我们要增加新条目时转向的组件;
  4. addListItem中,把 this.state.text 传入 this.props.store.addListItem。在与输入框绑定的 updateText 中会更新 this.state.text
  5. removeListItem 中调用 this.props.store.removeListItem 并传入条目;
  6. addItemToList 中调用 this.props.navigator.push,传入条目和数组存储两个参数;
  7. 在 render 方法中,通过属性解构数据存储:
    const { list } = this.props.store
    
  8. 在 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

就这么多!

查看最终的代码库,点击这里

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/jiangfei009003/article/details/73744758
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:02:14
  • 阅读 ( 1543 )
  • 分类:Go应用

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢