繁体   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