在开始之前,我已经检查了解决此问题的其他常见解决方案,例如从“ react-native”(而不是“ react-gesture-handler”)(我什至没有安装)中导入TouchableOpacity,或更改z -索引/绝对定位。它们都不起作用。
我是React Native的初学者。我正在尝试遵循本机反应课程,但是我在这个问题上陷入困境。我在真正的Android上使用Expo。我不使用模拟器。由于无法访问iOS,因此尚未在iOS上进行测试。当我将onPress添加到TouchableOpacity时,大多数情况下它在单击时会提供反馈(不透明度发生变化),但不会触发onPress事件。但是,有时它会起作用。当我按右边缘时,有时会触发该事件。这是一个示例:
index.js
import React from "react";
import Options from "./screens/Options";
export default function App() {
return <Options />;
}
Options.js
import React from "react";
import { View, StyleSheet } from "react-native";
import RowItem from "../components/RowItem";
import Constants from "expo-constants";
import styled from "styled-components";
import colors from "../constants/colors";
import { Entypo } from "@expo/vector-icons";
const SSeparator = styled.View`
background: ${colors.border};
height: ${StyleSheet.hairlineWidth}px;
margin-left: 20px;
`;
const SView = styled.View`
margin-top: ${Constants.statusBarHeight}px;
`;
export default () => {
return (
<SView>
<RowItem
title="Themes"
icon={
<Entypo
name="chevron-left"
size={20}
color={colors.blue}
onPress={() => alert("click")}
/>
}
/>
<SSeparator />
</SView>
);
};
RowItem.js
import React from "react";
import { TouchableOpacity, Text } from "react-native";
import styled from "styled-components";
import colors from "../constants/colors";
const SText = styled.Text`
font-size: 16px;
`;
const STouchableOpacity = styled.TouchableOpacity`
margin: 16px 20px;
flex-direction: row;
align-items: center;
justify-content: space-between;
`;
export default ({ title, icon, onPress }) => {
return (
<STouchableOpacity onPress={onPress}>
<SText>{title}</SText>
{icon}
</STouchableOpacity>
);
};
有什么想法吗?
答案 0 :(得分:0)
您可以这样尝试吗?
export default () => {
const testFunc = () =>{
alert('test')
}
return (
<SView>
<RowItem
title="Themes"
icon={
<Entypo
name="chevron-left"
size={20}
color={colors.blue}
onPress={testFunc}
/>
}
/>
<SSeparator />
</SView>
);
};
然后:
<STouchableOpacity onPress={()=>onPress()}>
<SText>{title}</SText>
{icon}
</STouchableOpacity>
答案 1 :(得分:0)
好吧,所以我终于注意到了这个错误,并且由于不注意而感到ham愧。我一直在阅读代码,但看不到明显的地方。
我错误地将onPress事件复制到了图标中,而不是将其直接放在RowItem中。
代替此:
<RowItem
title="Themes"
icon={
<Entypo
name="chevron-left"
size={20}
color={colors.blue}
onPress={() => alert("click")}
/>
}
/>
应该是这样:
<RowItem
title="Themes"
handlePress={() => alert("test")}
icon={<Entypo name="chevron-left" size={20} color={colors.blue} />}
/>
在RowItem.js中:
export default ({ title, icon, handlePress }) => {
return (
<STouchableOpacity onPress={() => handlePress()}>
<Text>{title}</Text>
{icon}
</STouchableOpacity>
);
};
现在该应用程序可以正常运行了。