gpt4 book ai didi

reactjs - 功能 react native 组件中的 onPress 不起作用

转载 作者:行者123 更新时间:2023-12-04 15:30:34 25 4
gpt4 key购买 nike

我正在尝试在 react-native 中创建一个简单的可重用按钮组件,但由于某种原因,onPress 函数从未被调用过。我发现的大多数线程只是立即调用函数或声明错误我相信我的声明应该没问题,我也尝试了几种不同的形式但无济于事

import React from 'react';
import { Text, Button, Image, TouchableOpacity } from 'react-native';
import { useHistory } from "react-router-native";
import { getFileUrl } from '../db/firebaseDb';
import styles from '../modules/Styles';

const GameIcon = (props) => {
const history = useHistory();

const handleClick = (pId) => {
console.log("TEST");
history.push("/game");
}

return (
<TouchableOpacity activeOpacity="0.5" onPress={handleClick}>
{(props.imageUrl)?<Image source={{uri: props.imageUrl}} style={{width: 32, height: 32}}/>:<Text>loading...</Text>}
<Button title={props.game.id} key={props.game.id} color={props.color} style={styles.buttons}/>
</TouchableOpacity>
)
}

export default GameIcon;

console.log 从未触发,我不知道为什么......我尝试将组件编写为函数 GameIcon ...我在没有 TouchableOpacity 的情况下尝试了这个,只是在返回函数中有按钮......在实际设备和模拟器上都不起作用

小更新:

我把返回函数的内容改成了:

<TouchableOpacity activeOpacity={0.5} onPress={()=>console.log("HELLO")}>
<Text title={props.game.id} key={props.game.id} color={props.color} style={styles.buttons}>{props.game.id}</Text>
</TouchableOpacity>

组件呈现没有任何错误或任何错误,它可以被选中并且不透明度正确更改但没有调用 onPress(因此没有控制台日志)

这似乎并不仅限于功能组件......

我将 react-native 文档中的按钮示例 1:1 添加到我的主屏幕上,并且永远不会调用 onPress 事件:

<Button
onPress={() => {
alert('You tapped the button!');
}}
title="Press Me"
/>

最佳答案

请尝试此代码。

import React from 'react';
import { Text, Button, Image, TouchableOpacity } from 'react-native';
import { useHistory } from "react-router-native";
import { getFileUrl } from '../db/firebaseDb';
import styles from '../modules/Styles';

const GameIcon = (props) => {
const history = useHistory();

const handleClick = (pId) => {
console.log("TEST");
history.push("/game");
}

return (
<TouchableOpacity activeOpacity={0.5} onPress={handleClick}>
<Text title={props.game.id} key={props.game.id} color={props.color} style={styles.buttons}>{props.game.id}</Text>
</TouchableOpacity>
)
}

export default GameIcon;

关于reactjs - 功能 react native 组件中的 onPress 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61317929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com