【问题标题】:How to pass variable to React Native's Alert.alert button's onPress?如何将变量传递给 React Native 的 Alert.alert 按钮的 onPress?
【发布时间】:2021-12-24 01:52:18
【问题描述】:

我正在尝试将对象/变量传递给 Alert.alert() 函数的按钮 onPress。不幸的是,我得到了“无敌”的结果。这是我的代码示例;

console.log("HERE ITEM SHOWS THE CORRECT VALUES", item);

Alert.alert(
    "Warning",
    "Test message",
    [
        {
            text: "Cancel",
            onPress: () => console.log("Cancel Pressed"),
            style: "cancel"
        },
        {
            text: "Start",
            onPress: () => { 
                    console.log("-----> HERE I CANNOT GET THE VALUES FOR ITEM", item);
            }
        }
    ]
    

);

如何传递值?非常感谢您的帮助:)

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    这是一个工作示例: https://snack.expo.dev/@gavindmello97/moody-raspberries

    <TouchableOpacity onPress = {() => {
        var tempVarForTest = "StackOverflow"
        Alert.alert(
          "Warning",
          "Test message",
          [
              {
                  text: "Cancel",
                  onPress: () => console.log("Cancel Pressed"),
                  style: "cancel"
              },
              {
                  text: "Start",
                  onPress: () => { 
                          alert("-----> HERE I CANNOT GET THE VALUES FOR ITEM "+ tempVarForTest);
                  }
              }
          ]
          
    
      );
    }}>
        <Text style={styles.paragraph}>
          Click me to open alertBox
        </Text>
      </TouchableOpacity>
    

    我使用了与您的问题相同的代码。请检查我是否遗漏了什么。由于它读取变量,它也可以读取对象、文本等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2020-03-30
      • 2019-04-03
      • 2021-06-01
      相关资源
      最近更新 更多