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

实现分类展示的filter功能

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

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


  
    
      All
    
    
      Active
    
    
      Completed
    
  

接下来写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

 this.props.onFilter("ALL")}>
    All
 

现在回到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

刷新后可以用filter功能啦。

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


        {this.props.count} count
        

App

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

你可能感兴趣的:(【ReactNative】入门:从todo App开始(6))