簡體   English   中英

如何刪除 ReactNative(JS) 列表中的特定元素

[英]How can you delete specific element in a list in ReactNative(JS)

我制作了一個待辦事項列表,其中無論我輸入什么都會被推送到一個數組。 當我映射數組時,我放了一個垃圾桶按鈕,他們可以在其中刪除“待辦事項”列表。 我嘗試了Splice方法,但它沒有用。 例如,我有一個列表,上面寫着:

“買牛奶”

“拿雞蛋”

如果我想刪除“Get Eggs”,它會刪除“Buy Milk”(它會刪除頂部的任何內容)。 有人可以幫助我如何實現這一目標。 這是我的代碼(React 本機代碼):

removeList = (item) => {
  let val = this.state.noteList;
  let arr = val.splice(item, 1); // <= this is what I did but it is removing the first element of the list

  let complete = this.state.completedTask;
  complete.push(arr);
 this.setState({
 arr
})
};

這是我的可觸摸不透明度:

<TouchableOpacity
  onPress={this.removeList}
  style={{
    height: deviceHeight / 10,
    width: deviceWidth / 6,
    backgroundColor: "#e6a25c",
    justifyContent: "center",
  }}
>
  <AntDesign
    name="checkcircleo"
    size={45}
    color="black"
    style={{ alignSelf: "center" }}
  />
</TouchableOpacity>;

對您來說,這似乎是一個愚蠢的問題,但我似乎無法弄清楚。

編輯:我試圖做一個平面列表而不是映射,但它對我不起作用。 難道我做錯了什么:

let newNote = [] // This is new NOTE and NOT THE COMPLETED SCREEN

newNote.push(

  <FlatList 
    data={this.state.noteList} 
    
    ListHeaderComponent={this.renderHeader}
    
    renderItem={({item,index}) => {
        <View style={{height:100,width:200,backgroundColor: "black"}}>
     
      <View style={styles.newBoxView}>
        <Text>{item}</Text>
      </View>
      </View>
     
    }}
  />
  
)

試試這個:

removeList = (item) => {
  let val = this.state.noteList;
  let arr;

  for (let i = 0; i < val.length; i++) {
    if (val[i] === item) {
      arr = val.splice(i, 1);
    }
  }

  let complete = this.state.completedTask;
  complete.push(arr);
};

我找到了我的答案,所以如果有人遇到同樣的問題,這里是代碼:

`deleteNote = (index) => {
console.log(index)
 let arr = this.state.noteList;
 delete arr[index]
 this.setState({
  activeCounter: Number(this.state.activeCounter - 1)
 })
}`

這是我的映射代碼:

  `this.state.noteList.map((item,index) => 
   <View style={styles.createBox}>  
   <View style={{flex:4,justifyContent: 'center',backgroundColor: 
   "lightpink",}}>
    <Text  style={{textAlign:'center',fontSize:deviceWidth/20,}}>
    {item.trim()}
  
  </Text>
</View>
<TouchableOpacity key={index} onPress={() => this.deleteNote(index)} style={{flex:1,justifyContent: 'center'}}>
<AntDesign  name="checkcircleo" style={{alignSelf:'center',backgroundColor: "#e6a25c"}} size={deviceWidth/5} color="black" />
</TouchableOpacity>
)`

我希望這有幫助。 這實際上花了我 1 周的時間才弄清楚,最后我弄明白了。

暫無
暫無

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

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