简体   繁体   中英

React Native, onPress not firing

Cannot get any output from my function test() which I have written in Boxes.js when I add onPress={test} to my View tag in Dice.js . I have tried to add test() on tags like Text , then it works, but not when I put it on the View tag.

Boxes.js:

import react from "react";
import { StyleSheet, Text, View, Image } from "react-native";

import Dice from "./Dice";
import PatternDivider from "./PatternDivider";

export function test() {
  console.log("hi");
}

export default class Boxes extends react.Component {
  render() {
    return (
      <View style={styles.box}>
        <Text style={styles.header}>Advice #117</Text>
        <Text style={styles.advice}>
          It is easy to sit up and take notice, what's difficult is getting uu
          and taking action
        </Text>
        <PatternDivider />
        <Dice />
      </View>
    );
  }
}

Dice.js:

import react from "react";
import { StyleSheet, Text, View, Image } from "react-native";

import { test } from "./Boxes";

export default class Dice extends react.Component {
  render() {
    return (
      <View style={styles.circle} onPress={test}>
        <Image
          source={require("../assets/icon-dice.png")}
          style={styles.dice}
        />
      </View>
    );
  }
}

If you wanna Dice to be clickable, use one the components that handles press events, like Pressable . Not all components accept an onPress property, View is one of them.

import react from "react";
import { StyleSheet, Text, View, Image, Pressable } from "react-native";

import { test } from "./Boxes";

export default class Dice extends react.Component {
  render() {
    return (
      <Pressable style={styles.circle} onPress={test}>
        <Image
          source={require("../assets/icon-dice.png")}
          style={styles.dice}
        />
      </Pressable>
    );
  }
}

React Native's View component doesn't have an onPress property https://reactnative.dev/docs/view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM