React Native中长按Pressable如何实现TextInput内容连续删除
Pressable长按持续删除TextInput内容解决方案
当前你写的onLongPress回调仅会在长按动作被识别时触发1次,无法实现连续调用删除函数的效果,要实现长按连续删除需要结合onPressIn、onPressOut事件配合定时器实现。
实现步骤
- 在组件内声明定时器引用,用来存储定时任务ID,方便后续销毁
- 在
onPressIn事件中实现逻辑:先延迟500ms(和RN默认长按触发时长一致)启动间隔定时器,每隔固定时长调用一次删除函数 - 在
onPressOut事件中销毁所有定时器,停止连续删除 - 保留单次点击删除逻辑,兼容短按场景
完整代码示例
import { useState, useRef, useCallback, useEffect } from 'react' import { Pressable, TextInput, StyleSheet } from 'react-native' import Icon from 'react-native-vector-icons/MaterialIcons' // 按你实际引入的图标库调整 const InputComponent = () => { const [inputValue, setInputValue] = useState('') // 存储长按延迟触发的定时器 const longPressTimerRef = useRef(null) // 存储连续删除的间隔定时器 const repeatDelTimerRef = useRef(null) // 删除单个字符逻辑 const delDigit = useCallback(() => { setInputValue(prev => prev.slice(0, -1)) }, []) // 按下Pressable时触发 const handlePressIn = useCallback(() => { // 长按500ms后启动连续删除 longPressTimerRef.current = setTimeout(() => { // 每100ms删除一次,可自行调整间隔时长控制删除速度 repeatDelTimerRef.current = setInterval(delDigit, 100) }, 500) }, [delDigit]) // 松开/移出Pressable时触发 const handlePressOut = useCallback(() => { // 清除所有定时器 if (longPressTimerRef.current) { clearTimeout(longPressTimerRef.current) longPressTimerRef.current = null } if (repeatDelTimerRef.current) { clearInterval(repeatDelTimerRef.current) repeatDelTimerRef.current = null } }, []) // 短按触发单次删除 const handlePress = useCallback(() => { // 避免长按结束后额外触发一次删除 if (!repeatDelTimerRef.current) { delDigit() } }, [delDigit]) // 组件卸载时销毁定时器避免内存泄漏 useEffect(() => { return () => { longPressTimerRef.current && clearTimeout(longPressTimerRef.current) repeatDelTimerRef.current && clearInterval(repeatDelTimerRef.current) } }, []) return ( <> <TextInput value={inputValue} onChangeText={setInputValue} style={styles.input} /> <Pressable style={({ pressed }) => [ styles.deleteStyle, { opacity: pressed ? 0.5 : 1, } ]} onPress={handlePress} onPressIn={handlePressIn} onPressOut={handlePressOut} > <Icon style={[{ color: '#FD6B89' }]} name="backspace" size={30} /> </Pressable> </> ) } const styles = StyleSheet.create({ // 按你实际的样式调整即可 input: { borderWidth: 1, borderColor: '#ccc', padding: 10, marginBottom: 20 }, deleteStyle: { padding: 10 } }) export default InputComponent
内容的提问来源于stack exchange,提问作者Eres Keanu Carreon
相关产品推荐
相关产品推荐

