美文网首页由浅入深的学习React全家桶
【ReactNative】入门:从todo App开始(6)

【ReactNative】入门:从todo App开始(6)

作者: LesliePeng | 来源:发表于2017-03-31 13:47 被阅读83次

实现分类展示的filter功能

首先在``footer文件中引入TouchableOpacity`,添加三个分类的tab:All显示全部todo items,Active显示尚未完成的items,Compeled显示已经完成的items。

import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

<View>
  <View>
    <TouchableOpacity>
      <Text>All</Text>
    </TouchableOpacity>
    <TouchableOpacity>
      <Text>Active</Text>
    </TouchableOpacity>
    <TouchableOpacity>
      <Text>Completed</Text>
    </TouchableOpacity>
  </View>
</View>

接下来写style

const styles = StyleSheet.create({
  container: {
    padding: 16,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between"
  },
  filters: {
    flexDirection: "row"
  },
  filter: {
    padding: 8,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: "transparent"
  },
  selected: {
   borderColor: "rgba(175, 47, 47, .2)"
 }
})

wire up这些style,然后用之前用到过的方法,来给每个filter添加选中的效果
还是先把filter这个prop单独拿出来:
const { filter } = this.props;
对于单独的每个filter

<TouchableOpacity
    style={[styles.filter, filter === "ALL" && styles.selected]}
    onPress={() => this.props.onFilter("ALL")}>
    <Text>All</Text>
 </TouchableOpacity>

现在回到App
首先在state中添加filter, 默认情况下是ALL,默认展示所有items。

this.state = {
      allComplete: false,
      filter: "ALL",
      value: '',
      items: [],
      dataSource: ds.cloneWithRows([])
    }

然后写一个过滤方法用来过滤当前的items数组,以返回对应的分类下的items

const filterItems = (filter, items) => {
  return items.filter((item) => {
    if (filter === "ALL") return true;
    if (filter === "ACTIVE") return !item.complete;
    if (filter === "COMPLETED") return item.complete;
  })
}

这个方法是写在component之外的public方法

然后handleFilter()方法

  handleFilter(filter) {
    this.setSource(this.state.items, filterItems(filter, this.state.items), { filter })
  }

其实就是setSource来渲染不一样的items到listView上,第二个参数就是新的要渲染的items。

为了当完成删除操作,或者其他改变item的操作后,这个filter也要对应的改变,所以也要修改handleRemove,handleToggle,handleAdd这几个方法

  handleRemoveItem(key) {
    const newItems = this.state.items.filter((item) => {
      return item.key !== key
    })
    this.setSource(newItems, filterItems(this.state.filter, newItems));
  }

另外几个一样的,就不写了。

这样就差最后一步了,wire up

<Footer
          onFilter={this.handleFilter}
          filter={this.state.filter} />

刷新后可以用filter功能啦。

最后,再添加一个count功能:
footer.js

<View style={styles.container}>
        <Text>{this.props.count} count</Text>
        <View style={styles.filters}>

App

<Footer
          count={filterItems("ACTIVE", this.state.items).length}
          onFilter={this.handleFilter}
          filter={this.state.filter} />

这样就能实时的显示,当前由多少待完成事项。

相关文章

网友评论

    本文标题:【ReactNative】入门:从todo App开始(6)

    本文链接:https://www.haomeiwen.com/subject/edqvottx.html