如何在Alert函数上调用onPress中的方法[React-Native]

问题描述 投票:12回答:1

如何在Alert函数上调用onPress中的方法[React-Native]

<Button
  onPress={{() => Alert.alert(
    'Alert Title',
    'alertMessage',
    [
      {text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
      {text: 'OK', onPress: () => {this.onDeleteBTN}},

    ],
    { cancelable: false }
  )}}
  >
      <Text> Delete Record </Text>
</Button>

在Alert Dialog上按OK按钮后我需要打电话

onDeleteBTN = () => {
    alert(' OnDelete');
}

{text: 'OK', onPress: () => {this.onDeleteBTN.bind(this)}},
{text: 'OK', onPress: () => {this.onDeleteBTN}},

这不行


javascript reactjs react-native react-native-android react-native-ios
1个回答
15
投票

第一个问题,Button组件有一个title道具,而不是像孩子一样有<Text>。第二个问题是你有一堆语法错误,并没有正确调用函数(或绑定)。如果你修复它,那它应该工作正常;例如:

alert = (msg) => {
  console.log(msg)
}

onDeleteBTN = () => {
  this.alert(' OnDelete')
}

render() {
  return (
    <View style={styles.container}>
      <Button
        title="Delete Record"
        onPress={() => Alert.alert(
          'Alert Title',
          'alertMessage',
          [
            {text: 'Cancel', onPress: () => console.log('Cancel Pressed!')},
            {text: 'OK', onPress: this.onDeleteBTN},
          ],
          { cancelable: false }
        )}
      />
    </View>
  );
}

注意:

  • 我不知道你的alert()函数应该做什么,所以我做了一个虚拟的登录到控制台。
  • 还有其他方法可以像调用onDeleteBTN()或绑定一样。
© www.soinside.com 2019 - 2024. All rights reserved.