我如何在React native中使用onLongPress触发事件?



我使用的是react-native!我想使用TouchableOpacity,以便当按钮按下约0.5秒时,hellofunction被执行并发出警报(' button Long pressed ');显示。

然而,使用我的代码,我必须点击并按住按钮两次而不是一次来运行它。

我如何修复我的代码?

这是我的代码

const App = () => {
const hellofunc = () => {
alert('Button Long Pressed');
};
return (
<TouchableOpacity style={styles.main} onLongPress={hellofunc}>
<Text>hi</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
main: {
backgroundColor: 'lightblue',
width: '100%',
height: 30,
},
});
export default App;

没有直接的方法,但是您可以添加两个事件keyUp和keyDown。为时间设置一个变量,当时间超过0.5时,可以将状态设置为long pressed key

let timeElapsed = 0;
let status = null;
document.addEventListener('keydown', checkLongPress);
document.addEventListener('keyUp', checkLongPress);
const getTimeMS = new Date().getTime(); // in ms
function checkLongPress() {
timeElapsed = timeElapsed === 0 getTimeMS() ? : getTimeMS() - timeElapsed;

if (timeElapsed /1000 >= threshold) { 
status = 'Long Pressed';
timeElapsed = 0;
}
}

最新更新