Javascript 如何从 onPress 调用方法 on Alert 功能 [React-Native]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44527230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:35:19  来源:igfitidea点击:

How can I call method from onPress on Alert function [React-Native]

javascriptreactjsreact-nativereact-native-androidreact-native-ios

提问by boy_v

How can I call method from onPress on Alert function [React-Native]

如何从 onPress 调用方法 on Alert 功能 [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>


After OK button on Alert Dialog I need to call

在 Alert Dialog 上的 OK 按钮之后,我需要调用

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


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


It's not work

这不工作



回答by Michael Cheng

First issue, the Buttoncomponent has a titleprop instead of having <Text>as a child. Second issue is that you have a bunch of syntax errors and are not calling functions (or binding) correctly. If you fix that, then it should work fine; for example:

第一个问题,Button组件有一个titleprop 而不是<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>
  );
}

Note:

笔记:

  • I don't know what your alert()function is supposed to do, so I made a dummy one that logs to console.
  • There are other ways of doing this like calling onDeleteBTN()or binding.
  • 我不知道你的alert()函数应该做什么,所以我做了一个虚拟的,记录到控制台。
  • 还有其他方法可以做到这一点,例如调用onDeleteBTN()或绑定。