简体   繁体   English

onPress 事件不适用于我的 React Native 代码中的自定义按钮?

[英]onPress event is not working with custom button in my React Native code?

I'm working on a React Native project as a beginner.作为初学者,我正在做一个 React Native 项目。 I'm creating a custom button called "RoundedButton" using touchableOpacity.我正在使用 touchableOpacity 创建一个名为“RoundedButton”的自定义按钮。 But after creating this button when I use this and try to trigger an event using onPress like <RoundedButton onPress = {some function}/> it does not work.但是,当我使用这个按钮并尝试使用 onPress 触发事件(如 <RoundedButton onPress = {some function}/>)时,它不起作用。 Here is my code:这是我的代码:

my RoundedButton.js code :我的 RoundedButton.js 代码

import React from 'react';
import {TouchableOpacity, Text, StyleSheet} from 'react-native';
import {colors} from '../utils/colors';

export const RoundedButton = ({
  style = {},
  textStyle = {},
  size = 125,
  ...props
}) => {
  return (
    <TouchableOpacity style ={[styles(size).radius, style]}>
      <Text style = {[styles(size).text, textStyle]}>{props.title}</Text>
    </TouchableOpacity>
  )

};

my Timer.js code where I uses the above custom button :我使用上述自定义按钮的 Timer.js 代码

import React, {useState} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {colors} from '../../utils/colors';
import {fontSizes, spacing} from '../../utils/sizes'
import {Countdown} from '../../components/Countdown';
import {RoundedButton} from '../../components/RoundedButton';

export const Timer = ({focusSubject}) => {
  const [isStarted, setIsStarted] = useState("false");
  const onPress = () => setIsStarted("true");
  
  return (
    <View style={styles.container}>
      <View style={styles.countdown}>
        <Countdown isPaused={!isStarted}/>
      </View>      
      <View>
        <Text style={styles.title}>Focusing on: </Text>
        <Text style={styles.task}>{focusSubject}</Text>
      </View>    
      <RoundedButton title="Start" size={50} onPress={onPress}/> 
      <Text style={{color: 'white'}}>{isStarted ? "True" : "False"}</Text>
    </View>    
  )
};

I have not included styles code to make it simpler to find the issue.我没有包含 styles 代码,以便更容易找到问题。 I want to know the correct method to use onPress functionality in React Native.我想知道在 React Native 中使用 onPress 功能的正确方法。 Please help as soon as possible.请尽快提供帮助。 No error is shown, App is working but the pressing event is not working, so I am not able to find out the actual issue.没有显示错误,应用程序正在运行,但按下事件不起作用,所以我无法找出实际问题。

This is because you haven't passed onPress to TouchableOpacity .这是因为您没有将onPress传递给TouchableOpacity Just pass the prop and it should work just fine.只需通过道具,它应该可以正常工作。

 <TouchableOpacity style ={[styles(size).radius, style]} onPress={props.onPress}> <Text style = {[styles(size).text, textStyle]}>{props.title}</Text> </TouchableOpacity>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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