簡體   English   中英

如何重新渲染 Flatlist React Native?

[英]How make re-render Flatlist React Native?

我正在為 TodoList 做一個搜索過濾器。 在 todoList 中,我使用一個函數來渲染名為renderItem項目,但是當我在inputText寫入搜索到的項目時,我不知道如何重新渲染

有人能幫我嗎?

靜態容器.js

import * as React from 'react';
import { FlatList, Text, View, StyleSheet, TouchableOpacity, TextInput } from 'react-native';

export default class StaticCounter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filter: '',
      name: '',
    }
    this.renderItem = this.renderItem.bind(this)
    this.setState = this.setState.bind(this)
  }
  setState(text){
    this.state.filter = text
    alert(JSON.stringify(this.state.filter))
    this.renderItem
  }
  renderItem(obj){
    if (this.state.filter != '') {
      if (obj.item.desc.startsWith(this.state.filter)) {
        console.log(typeof(obj.item.desc));
        let key = obj.item.key      
        return(
          <TouchableOpacity style={styles.container} onPress={()=> this.props.acessarDados(key)}>
            <Text style={styles.cel}>{obj.item.desc}</Text>
          </TouchableOpacity>
        )
      }else{

      }
    }else{
      let key = obj.item.key      
      return(
        <TouchableOpacity style={styles.container} onPress={()=> this.props.acessarDados(key)}>
          <Text style={styles.cel}>{obj.item.desc}</Text>
        </TouchableOpacity>
      )
    }

    }
    render() {
      return (
        <View>
          <FlatList style={styles.lista} data={this.props.itens} renderItem={this.renderItem}/>
          <TextInput style={styles.input} onChangeText={(text) =>{this.setState(text)}}/>
        </View>
      );
    }
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: '#fff',
      justifyContent: 'center',
    },
    lista: {
      marginTop: 90,
    },
    cel:{
      paddingVertical: 20,
      backgroundColor: '#E4EBEE',
      fontSize: 18,
      marginBottom: 2,
    },
    inputView:{
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
    },
    input:{
      backgroundColor: '#fff',
      borderColor: '#ccc',
      borderWidth: 3,
      padding: 15,
      margin:20,
      color: '#3d3d3d'
    }
  });


你必須過濾你傳遞給 flatlist 的數據

state = {todoList: props.items  } 

filterTodo = (inputText) => {
  const filteredList = this.state.todolist.filter(todo => todo.includes(inputText));
  this.setState({todolist: filteredList })
}

那么你的 flatlist 的數據就變成了 this.state.todolist。 只是要清楚渲染項是從數據數組中的每個數據點渲染的組件,整個列表的邏輯不應該在那里完成,如果您不想顯示任何數據,它應該是數據道具

data={someCondition? this.props.todolist: [] }

我認為您在 flatlist data={this.props.itens} 中有一個錯字,如果它是一個非常大的列表,您需要更優化的后端搜索,這將適用於一個簡單的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM