首页 > 解决方案 > 在 React Native 中按下按钮删除内容

问题描述

我的课堂上有以下内容:

constructor(props) {
  super(props);
  this.state={title: this.props.title, comment: '', units:'', rows: 1}
  this.renderRows = this.renderRows.bind(this);
  this.removeRow = this.removeRow.bind(this);
}

renderMore() {
  let rowsAux = this.state.rows + 1;
  this.setState({
    rows: rowsAux
  })
}

removeRow(i) {
  console.log('selected row ' + i);
  this.deleteById(i); // something like this???
}

renderRows() {

  let max;
  if (this.state.rows > 4) {
    max = 4;
  } else {
    max = this.state.rows;
  }
  const options = [];

    for (let i = 0; i < max; i++) {
      let zI = 999 - i;
      options.push(<View id='i' style={{ flexDirection: 'row', zIndex: zI}}>
      <DropDownPicker
          items={[
              {label: 'Lunes', value: 'Lunes'},
              {label: 'Martes', value: 'Martes'},
              {label: 'Miércoles', value: 'Miércoles'},
              {label: 'Jueves', value: 'Jueves'},
              {label: 'Viernes', value: 'Viernes'}
          ]}
          defaultValue={'Lunes'}
          containerStyle={{height: 50}}
          style={{marginTop: 5, backgroundColor: '#fafafa',width: 150,
          borderTopLeftRadius: 10, borderTopRightRadius: 10,
          borderBottomLeftRadius: 10, borderBottomRightRadius: 10}}
          dropDownStyle={{backgroundColor: '#fafafa'}}
      />
      <DropDownPicker
          items={[
              {label: '8 a 12hs', value: '8 a 12'},
              {label: '12 a 16hs', value: '12 a 16'},
              {label: '16 a 20hs', value: '16 a 20'}
          ]}
          defaultValue={'8 a 12'}
          containerStyle={{marginLeft: 10, height: 50}}
          style={{marginTop: 5, backgroundColor: '#fafafa',width: 150,
          borderTopLeftRadius: 10, borderTopRightRadius: 10,
          borderBottomLeftRadius: 10, borderBottomRightRadius: 10}}
          dropDownStyle={{backgroundColor: '#fafafa'}}
      />
      <TouchableOpacity onPress={() => {this.removeRow(i)}}>
        <Ionicons style={{marginTop: 12, marginLeft: 15}} name='ios-trash' color={'gray'} size={28}/>
      </TouchableOpacity>
      </View>);
    }

  return options;
}

我想要做的是在函数 renderRows 内的 IoniIcon ('ios-trash') 中添加一个 onPress 方法,该方法删除其对应的视图和那个视图。我怎样才能做到这一点?

更新:我的问题实际上是关于我应该如何实现我的 onPress 方法以指示它必须删除其父视图。我想也许我可以向父视图添加某种 ID,然后将其传递给 onPress 方法以删除该特定视图。

标签: javascriptreact-native

解决方案


将 Ionicons 包裹在 TouchableOpacity 中。

<TouchableOpacity onPress={}>
      <Ionicons style={{marginTop: 12, marginLeft: 15}} name='ios-trash' color={'gray'} size={28}/>
</TouchableOpacity>

推荐阅读