我有一个计数器状态和四个按钮,每个按钮都传递了相同的onPress函数,该函数会将计数器值增加1。
如果我极快地交替按下任意两个不同的按钮(即按钮2->按钮4->按钮2->按钮4),则onPress函数有时会被忽略(您可以看到计数器值没有增加) )。我希望点击后计数器会增加。
但是,如果我连续按下相同的按钮(快速按住按钮2),问题似乎没有发生。
这是描述问题的最小示例:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Image, TouchableOpacity, Dimensions } from 'react-native';
export default class TestCount extends Component {
constructor(props) {
super(props);
this.state = {
clickCount: 0,
};
}
increaseCount = () => {
this.setState(function(prevState, props){
return {
clickCount: prevState.clickCount + 1
}
})
}
render() {
const { clickCount } = this.state;
return (
<View style={styles.container}>
<View style={styles.countBoard}>
<Text style={styles.question}>{clickCount}</Text>
</View>
<View style={styles.butons}>
<TouchableOpacity style={styles.choice}>
<Text style={styles.btnText} onPress={this.increaseCount}>Button 1</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.choice}>
<Text style={styles.btnText} onPress={this.increaseCount}>Button 2</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.choice}>
<Text style={styles.btnText} onPress={this.increaseCount}>Button 3</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.choice}>
<Text style={styles.btnText} onPress={this.increaseCount}>Button 4</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const BtnWidth = Math.floor((Dimensions.get('window').width - 40) / 2);
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
justifyContent: 'center',
alignItems: 'center',
},
countBoard: {
height: 200,
justifyContent: 'center',
alignItems: 'center',
marginLeft: 20,
marginRight: 20,
marginBottom: 15,
},
question: {
fontSize: 40,
fontWeight: '600',
},
btnText: {
fontSize: 22,
borderColor: '#595959',
},
butons: {
width: '100%',
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
},
choice: {
width: BtnWidth,
height: 50,
borderWidth: 1
}
});
答案 0 :(得分:0)
这可能不是React Native的问题,而是手机的正常功能。
在某些无法处理两次触摸的手机中,如果按两点,它将按两点的“中点”。
因此,当您快速按下时,有时您会同时触摸两次,并且在“中间”只会变成一次。
当我按下电话时,这种情况在我身上发生了很多,但是它不起作用,然后我意识到它不起作用的原因是因为握住电话的手的一部分正在触摸屏幕,在屏幕上创建两个点,然后在两个点的中间单击它。
答案 1 :(得分:0)
找到了解决方案,这显然是一个非常小的错误-.-,我不小心将onPress
放在了<Text>
组件而不是TouchableOpacity
上。因此,当我在没有文本的区域上按按钮时,该按钮看起来像冻结了。