React Native TouchableOpacity没有响应

kx7yvsdv  于 2023-02-19  发布在  React
关注(0)|答案(1)|浏览(213)

我对React native很陌生,最近一直在摆弄它。每次我使用其中一个可触摸组件时都会遇到问题。由于某种原因,当我点击可触摸组件时,它没有响应。我尝试寻找其他解决方案,但没有找到。(如果你需要知道的话,我也在使用Expo)

import {
  ImageBackground,
  StyleSheet,
  View,
  SafeAreaView,
  Platform,
  StatusBar,
  Text,
  TouchableOpacity,
} from "react-native";

const StartScreen = () => {
  return (
    <ImageBackground
      source={require("../assets/Background.png")}
      style={{ flex: 1 }}
    >
      <SafeAreaView style={styles.ContentArea}>
        <TouchableOpacity onPress={console.log("Button pressed!")}>
          <View style={styles.nextButton}>
            <Text style={{ fontWeight: "bold", fontSize: 15 }}>Test</Text>
          </View>
        </TouchableOpacity>
      </SafeAreaView>
    </ImageBackground>
  );
};

const styles = StyleSheet.create({
  ContentArea: {
    flex: 1,
    paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    justifyContent: "flex-end",
    alignItems: "center",
  },

  nextButton: {
    width: 150,
    height: 40,
    backgroundColor: "tomato",
    marginBottom: 45,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 50,
  },
});

export default StartScreen;
oaxa6hgo

oaxa6hgo1#

你在onPress方法中传递了一个函数调用。这使得console.log在render上运行。console.log()返回undefined,所以你的onPress属性最终是undefined本身。你要做的是传递一个对函数的引用,或者是一个匿名函数。下面是一个例子:

...

<TouchableOpacity onPress={() => console.log("Button pressed!")}>
  <View style={styles.nextButton}>
    <Text style={{ fontWeight: "bold", fontSize: 15 }}>Test</Text>
   </View>
</TouchableOpacity>

...

相关问题