使用自定义Listview从列表中删除行

时间:2019-03-20 11:48:11

标签: javascript react-native

我希望能够通过向行项目添加“ x”按钮来从自定义列表视图中删除行。我似乎无法弄清楚该如何做。我试图将一个函数传递给该行并删除索引,但是我不确定该怎么做。我对js比较陌生。

还有其他方法或可用于执行此操作的节点吗?

该行如何将数据传递给deleteData? 现在,index参数实际上不是索引。

row.js

const CustomRow = ({ title, description, image_url, handleRemovePress }) => (
<View style={styles.container}>
    <Image source={{ uri: image_url }} style={styles.photo} />
    <View style={styles.container_text}>
        <Text style={styles.title}>
            {title}
        </Text>
        <Text style={styles.description}>
            {description}
        </Text>
        <TouchableOpacity onPress={handleRemovePress} style={styles.removeButton}>
          <Text style={styles.removeButtonText}>X</Text>
        </TouchableOpacity>
    </View>
 </View>
);

customListview.js

const CustomListview = ({ itemList }) => (
    <View style={styles.container}>
        <FlatList
                data={itemList}
                extraData={itemList}
                renderItem={({ item }) => <CustomRow
                    title={item.title}
                    description={item.description}
                    image_url={item.image_url}
                    handleRemovePress={item.handleRemovePress}
                />}
            />
    </View>
);

screen.js

constructor(props) {
super(props);
this.array = [
  {
    key: '1', 
    title: 'Exercise A',
    description: 'Lorem ipsum',
    image_url: '', 
    handleRemovePress: this.deleteData
  },
],
  this.state = {
    arrayHolder: [],
      textInput_Holder: ''
      }
  }

  deleteData(index){
       this.array.splice(index, 1);
        this.setState({ arrayHolder: [...this.array] })
      }
  render() {
    return (
      <View style={styles.container}>       
      <CustomListview
        itemList={this.state.arrayHolder}/>
     </View>
    );
  }

1 个答案:

答案 0 :(得分:1)

在screen.js上尝试一下:

编辑:

     constructor(props) {
          super(props);

            array = [
            {
              key: '1', 
              title: 'Exercise A',
              description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore',
              image_url: 'https://www.sivananda.at/images/ueber-uns/swami_vishnudevananda_portait.jpg', 
              handleRemovePress: this.deleteData
            },
          ]
            state = {
              arrayHolder: this.array,


                textInput_Holder: ''
                }

             deleteData = (index) =>{
               let tempArray = this.state.arrayHolder
               tempArray.splice(index, 1);
              this.setState({arrayHolder: tempArray})
            }

            render(){
              return <CustomListview itemList={this.state.arrayHolder}/>
            }
          }