如何在redux-form中用useRef Hook实现键盘Next键聚焦下一个TextInput
在函数组件中结合redux-form和useRef实现Next键聚焦输入框
我来帮你搞定这个问题!其实核心是要正确把useRef的引用传递到内部的TextInput组件上——因为redux-form的Field会包装你的自定义输入组件,直接给Field加ref拿不到TextInput实例,得换个方式传递。
关键修正思路
- 别给Field组件加ref,改用自定义props(比如
refField)把useRef对象传给MyTextInput - 在
MyTextInput里把接收到的refField直接绑定到TextInput的ref属性上 - 确保
onSubmitEditing事件正确触发聚焦逻辑
修正后的父组件(函数组件)代码
import { useRef } from 'react'; import { Field } from 'redux-form'; const YourFormComponent = () => { // 创建两个ref分别指向两个输入框 const inputEl1 = useRef(null); const inputEl2 = useRef(null); // 第一个输入框按下Next时的聚焦回调 const focusNextInput = () => { // 加个判断避免空引用报错 if (inputEl2.current) { inputEl2.current.focus(); } }; return ( <> <Field name="first_name" component={MyTextInput} placeholder="First name" returnKeyType="next" // 把返回键设置为Next样式 onEnter={focusNextInput} // 传递聚焦回调 refField={inputEl1} // 把ref传递给MyTextInput /> <Field name="last_name" component={MyTextInput} placeholder="Last name" refField={inputEl2} // 传递第二个输入框的ref /> </> ); };
修正后的MyTextInput组件代码
import React, { Component } from 'react'; import { View, TextInput } from 'react-native'; import Colors from './your-path-to-colors'; // 替换成你的颜色文件路径 class MyTextInput extends Component { state = { passwordVisibility: false, undelineColor: Colors.DEFAULT_UNDERLINE_COLOR, // 替换成你的默认下划线颜色 }; render() { const { input: { value, onChange, onBlur }, meta: { touched, error }, keyboardType, placeholder, secureTextEntry, editable, selectTextOnFocus, style, selectable, customValue, underlineColorAndroid, autoFocus, maxLength, returnKeyType, onEnter, refField, // 接收父组件传递的ref } = this.props; const { passwordVisibility, undelineColor } = this.state; return ( <View style={{ marginVertical: 8 }}> <TextInput style={[{ height: 50, paddingLeft: 20, color: Colors.SECONDARY_COMMON, }, style]} onBlur={val => onBlur(val)} keyboardType={keyboardType} underlineColorAndroid={undelineColor || underlineColorAndroid} placeholder={placeholder} returnKeyType={returnKeyType || 'go'} value={customValue || value.toString()} onChangeText={onChange} maxLength={maxLength} onSubmitEditing={onEnter} // 绑定提交事件,触发聚焦回调 ref={refField} // 把ref绑定到TextInput上,让父组件能拿到原生实例 /> {/* 可选:添加错误提示 */} {touched && error && ( <Text style={{ color: 'red', marginTop: 4, paddingLeft: 20 }}> {error} </Text> )} </View> ); } } export default MyTextInput;
为什么这样能行?
- redux-form的Field组件会自动把你传递的自定义props(比如
refField、onEnter)透传给MyTextInput - 通过
refField把父组件的useRef对象绑定到TextInput上,父组件就能通过inputEl2.current拿到TextInput的原生实例,进而调用focus()方法 onSubmitEditing是React Native TextInput的原生事件,当用户按下返回键(这里设置为Next)时会触发,刚好执行聚焦下一个输入框的逻辑
内容的提问来源于stack exchange,提问作者shubham choudhary
相关产品推荐
相关产品推荐

