在React-Native中单击按钮删除表单时出错

时间:2017-06-09 04:22:07

标签: reactjs react-native

我是React-Native的新手。我想删除单击按钮的表单。但是,如果我添加多个表单,然后单击删除表单,最后一个按钮删除,然后删除所有表单。然而,我想如果我点击最后一个表格中的按钮删除,那么只需删除最后一个表格。

这是我的代码

class.....{
 constructor(props) {
    super(props);
    this.state = {
      showMaterial: [],
    };
    this.onAddBtnClick = this.onAddBtnClick.bind(this);
  }
 render(){
  return(
   <Icon name='add' onPress={() => this.onAddBtnClick()}/>

    {this.state.showMaterial.map((input, index)=>{
      return input;   
      })
    }
  );
 }

 onAddBtnClick(event) {
    const showMaterial = this.state.showMaterial;
        this.setState({
            showMaterial: showMaterial.concat(
                <List key={showMaterial.length}>
                  <ListItem>
                      <Text >Description</Text>
                      <Icon name='remove' onPress={() => this.onRemove()}/>
                      <Input style={{height: 30}} placeholderTextColor='lightgray' placeholder="Description" multiline={true} onChangeText={(description) => this.setState({description})}/>

                  </ListItem>
              </List>
              )
        });
  }

  onRemove(){
    this.setState({
      showMaterial:this.state.showMaterial.filter((e, i) => !this.state.showMaterial)
    })
  }

}

1 个答案:

答案 0 :(得分:0)

您可以尝试传递列表的ID以删除方法

onAddBtnClick(event) {
    const showMaterial = this.state.showMaterial;
        this.setState({
            showMaterial: showMaterial.concat(
                <List key={showMaterial.length}>
                  <ListItem>
                      <Text >Description</Text>
                      <Icon name='remove' onPress={() => this.onRemove(showMaterial.length-1)}/>
                      <Input style={{height: 30}} placeholderTextColor='lightgray' placeholder="Description" multiline={true} onChangeText={(description) => this.setState({description})}/>

                  </ListItem>
              </List>
              )
        });
  }

  onRemove(idx){
    this.setState({
      showMaterial:this.state.showMaterial.splice(idx,1)
    })
  }