Home > database >  React Native, onPress not firing
React Native, onPress not firing

Time:07-04

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>
    );
  }
}

CodePudding user response:

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>
    );
  }
}

CodePudding user response:

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

  • Related