[英]Getting events from a disabled TouchableOpacticity in React Native
I want to collect some data about how many users are pressing a disabled button (implemented using TouchableOpacity
) in my React-Native app?我想收集一些关于有多少用户在我的 React-Native 应用程序中按下禁用按钮(使用
TouchableOpacity
实现)的数据? Since I am passing disabled=true
to the element, the onPress
event handler is not getting executed?由于我将
disabled=true
传递给元素,因此onPress
事件处理程序没有被执行?
Is there any way to listen to events from a disabled TouchableOpacity
.有什么方法可以监听来自禁用的
TouchableOpacity
的事件。
My last resort is to simply make the button look disabled, and capture the onPress
event, but I am looking for some tricks to capture event from the disabled element directly.我最后的手段是简单地使按钮看起来被禁用,并捕获
onPress
事件,但我正在寻找一些技巧来直接从禁用元素中捕获事件。
According to the docs, TouchableOpacity
inherits all the props from TouchableWithoutFeedback , and the disabled prop there disables all interactions, so the onPress event is never fired.根据文档,
TouchableOpacity
继承了TouchableWithoutFeedback的所有道具,并且禁用了那里的道具禁用了所有交互,因此永远不会触发 onPress 事件。 As you guessed, the best course of action is to make the button appear disable:如您所料,最好的做法是使按钮显示为禁用:
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
TouchableOpacity,
} from 'react-native';
import LabeledSwitch from './components/LabeledSwitch';
export default function App() {
const [buttonIsActive, setButtonIsActive] = useState(false);
const onButtonPressed = ({ nativeEvent }) => {
if (!buttonIsActive) {
// do your data gathering
console.log(nativeEvent);
return;
}
// do default button stuff
};
return (
<View style={styles.container}>
<LabeledSwitch
label="Set button active"
currentValueMessage={
'Button is ' + (buttonIsActive ? 'active' : 'inactive')
}
value={buttonIsActive}
onValueChange={setButtonIsActive}
/>
<TouchableOpacity
style={[styles.touchable, !buttonIsActive && styles.disabledButton]}
onPress={onButtonPressed}
// since we are faking disabling the button we will need to
// hide touch animations when the button is disabled
activeOpacity={buttonIsActive ? 0.2 :styles.disabledButton.opacity}
>
<Text style={[styles.text,!buttonIsActive && styles.disabledButton]}>Press me</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
touchable: {
borderRadius: 10,
backgroundColor: 'lightgreen',
borderColor: 'green',
borderWidth: 1,
alignItems: 'center',
padding: 5,
margin: 2,
width: '50%',
alignSelf: 'center',
},
disabledButton: {
opacity: 0.8,
},
text:{
color:'darkgreen',
fontSize:18
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.