簡體   English   中英

如何更新 FlatList 項目的屬性?

[英]How to update the attribute of an item of a FlatList?

我編寫了一個 Android 應用程序,它由 TextInput、Button 和 FlatList 組成。 使用 TextInput 中寫入的每個名稱,平面列表中都會有一個項目。 Item 標題將是 TextInput 內容,列表項旁邊將有兩個按鈕和一個文本。 一個按鈕用於將 Text 顯示的數字增加 1,另一個按鈕用於減少。 這是我的代碼:

import React, {Component} from 'react';
import {
  View,
  Text,
  TextInput,
  FlatList,
  TouchableOpacity,

} from 'react-native';
import { ListItem, SearchBar} from 'react-native-elements';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      task: "",
      task_array: [],


    };
  }

  ChangeText = (some_task) => {
    this.setState({task: some_task});
  };
  pushAdd = () => {
    let contact = {
      name: this.state.task,
      counter: 0,
    };
    this.setState({task_array: [...this.state.task_array, contact]});
  };








  renderListItem = ({item}) => {
   return(
     <View style={{flexDirection: 'row'}}>
     <ListItem title={item.name} style={{width:'75%', marginLeft:20}}></ListItem>
     <View style={{flexDirection:'row'}}>
         <TouchableOpacity style={{ backgroundColor: 'blueviolet', height: 20, width: 20, borderRadius: 50}} onPress={()=> item={name:item.name, counter:item.counter + 1}}><Text>+</Text></TouchableOpacity>
         <Text>{item.counter}</Text>
  //main problem       <TouchableOpacity style={{ backgroundColor: 'blueviolet', height: 20, width: 20, borderRadius: 50 }} onPress={() => item = { name: item.name, counter: item.counter - 1 }}><Text>-</Text></TouchableOpacity>

     </View>

     </View>

   );
  };


render() {
  return(
    <View style={{ backgroundColor: 'mediumturquoise', width:'100%', height:'100%'}}>
    <FlatList 
      data = {this.state.task_array}
      renderItem = {this.renderListItem}
      keyExtractor = {(item) => item.name}>
    </FlatList>
    <View style = {{flexDirection : 'row', alignContent:'center', alignItems:'center'}}>
        <TextInput onChangeText={this.ChangeText} style={{ backgroundColor: 'burlywood', height:50, width:'75%', borderRadius:30, marginBottom:20, marginLeft:20, marginRight:20}}></TextInput>
        <TouchableOpacity style={{ backgroundColor: 'chocolate', height:40, width:50, borderRadius:10, marginBottom:20}} onPress={this.pushAdd}></TouchableOpacity>
    </View>
    </View>
  );
  }
};

export default App;

我用評論“主要問題”指出了有問題的行。 增加和減少按鈕不起作用,當我在應用程序中按下它們時,文本中的數字保持不變。 我應該對我的增加和減少按鈕的 onPress 方法執行什么更改以使它們工作?

在 React 中,您不能直接操作數據(就像您在 +/- 按鈕 onPress 方法中所做的那樣)。 這將沒有效果,相反,您需要使用setState適當地更改 state

最快的解決方法是改變

// this
renderListItem = ({item}) => {
// to this
renderListItem = ({item, index}) => {

知道渲染項目的索引。 然后,更改這些項目內的增量/減量按鈕的onPress方法以使用setState

// from this
onPress={()=> item={name:item.name, counter:item.counter + 1}}
// to this
onPress={() =>
          this.setState({
            task_array: this.state.task_array
              .map((item, itemIndex) =>
                itemIndex !== index
                  ? item
                  : {
                    ...item,
                    counter: item.counter + 1
                  })
          })}

這里發生的是我們使用數組的.map()方法從舊的 task_array 創建一個新的 task_array,除了被點擊的一個元素之外,每個元素都保持不變——我們通過比較索引來定義它。 在這種情況下,我們增加它的計數器並使用 this.setState 為this.setState分配新值

Max的回答是一種實現方式,但是性能不好,每次child更新,all view都會重新渲染一遍。 這是我的解決方案:
首先,在父組件中注冊一個事件,接收子更新通知。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      task: "",
      task_array: [],
    };
  }

// register the event,
componentDidMount() {
    DeviceEventEmitter.addListener('itemUpdate', this.updateData)
  }

  componentWillUnmount () {
    DeviceEventEmitter.removeListener('ModalVisible', this.updateData)
  }
  updateData = (params) => {
      let copyTaskArray = {...this.state.task_array}
      copyTaskArray[params.index].counter = params.counter
      this.state.task_array = copyTaskArray
  }

那么我們應該將 FlatList 項移動到單個組件中,並讓它更新值

import React,{Component} from 'react';
import { View, TouchableOpacity,DeviceEventEmitter} from 'react-native';
export default class Item extends Component{
    constructor(props) {
      super(props);
      this.state = {
        counter:this.props.item.counter
      };
    }

    plus = () => {
      let oldCounter = this.state.counter;
      let newCounter = oldCounter +1;
      this.setState({
         counter: newCounter
      })
      // notify the parent
      DeviceEventEmitter.emit("itemUpdate",{index:this.props.index,counter:this.state.counter})
    }

    reduce = () => {
       // the same with plus, only oldCounter -1
    }

    render() {
      return(
       <View key={this.props.index} style={{flexDirection: 'row'}}>
       <ListItem title={this.props.item.name} style={{width:'75%', marginLeft:20}}></ListItem>
       <View style={{flexDirection:'row'}}>
           <TouchableOpacity style={{ backgroundColor: 'blueviolet', height: 20, width: 20, borderRadius: 50}} onPress={this.plus}>
           <Text>+</Text>
           </TouchableOpacity>
           <Text>{his.props.item.counter}</Text>
     <TouchableOpacity style={{ backgroundColor: 'blueviolet', height: 20, width: 20, borderRadius: 50 }} onPress={this.reduce}>
      <Text>-</Text>
     </TouchableOpacity>
       </View>
       </View>
    ) 
  }
}

在這種情況下,當項目在屏幕上滾動並重新創建時,該值仍然存在。
最后,我們應該更改父項的 renderListItem 方法。

renderListItem = ({item, index}) => {
    return(
     <Item index={index} item={item} ></Item>       

    );
   }

我希望這可以幫助你。

暫無
暫無

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

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