[英]onPress event is not working with custom button in my React Native code?
作为初学者,我正在做一个 React Native 项目。 我正在使用 touchableOpacity 创建一个名为“RoundedButton”的自定义按钮。 但是,当我使用这个按钮并尝试使用 onPress 触发事件(如 <RoundedButton onPress = {some function}/>)时,它不起作用。 这是我的代码:
我的 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>
)
};
我使用上述自定义按钮的 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>
)
};
我没有包含 styles 代码,以便更容易找到问题。 我想知道在 React Native 中使用 onPress 功能的正确方法。 请尽快提供帮助。 没有显示错误,应用程序正在运行,但按下事件不起作用,所以我无法找出实际问题。
这是因为您没有将onPress
传递给TouchableOpacity
。 只需通过道具,它应该可以正常工作。
<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.