【react native】ScrollView的触摸事件与TouchableWithoutFeedback的点击事件冲突
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
触摸事件在React Native中是通过传递给各个组件的onStartShouldSetResponder和onStartShouldSetResponderCapture方法来处理的。当ScrollView和TouchableWithoutFeedback组件同时处于屏幕上时,可能会发生事件冲突。
为了解决这个问题,可以使用ScrollView的scrollEventThrottle
属性来减少事件的触发频率,或者使用PanResponder来处理更复杂的触摸事件。
以下是一个简单的例子,展示如何使用PanResponder
来解决这个问题:
import React, { Component } from 'react';
import { View, ScrollView, Text, PanResponder, TouchableWithoutFeedback, StyleSheet } from 'react-native';
export default class TouchableInScrollView extends Component {
constructor(props) {
super(props);
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
});
}
render() {
return (
<ScrollView style={styles.scrollView}>
<View style={styles.container}>
{/* 在这里放置你的内容 */}
<TouchableWithoutFeedback
style={styles.button}
{...this._panResponder.panHandlers}
onPress={this.handlePress}>
<Text>Click Me!</Text>
</TouchableWithoutFeedback>
</View>
</ScrollView>
);
}
handlePress = () => {
console.log('Button clicked!');
};
}
const styles = StyleSheet.create({
scrollView: {},
container: {
flex: 1,
padding: 20,
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginBottom: 10,
},
});
在这个例子中,我们创建了一个PanResponder
,并将其panHandlers
添加到了TouchableWithoutFeedback
组件中。这样,当用户触摸按钮时,PanResponder
会拦截触摸事件,并且只有在用户确实移动手指时才会处理滑动事件,否则会处理点击事件。这样就可以避免在ScrollView中点击事件与滑动事件冲突的问题。
评论已关闭