如何在使用自定义文本输入时更改文本输入的焦点



1.这是我的自定义文本输入自定义组件,我定义了我想在其中使用的props-ref母组件

export const InputField = ({
placeholder,
onChangeText,
placeholderTextColor,
showSecureIcon,
isSecure,
onPressIcon,
keyboardType,
returnKeyType,
maxLength,
secureIconColor,
handleUseCallBack,
ref,
value
}) => {

return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder={placeholder}
onChangeText={onChangeText}
placeholderTextColor={placeholderTextColor}
autoCapitalize="none"
secureTextEntry={isSecure}
keyboardType={keyboardType}
returnKeyType={returnKeyType}
maxLength={maxLength}
value={value}
ref={ref}
/>
<View style={styles.iconContainer}>
{showSecureIcon ?
<TouchableOpacity
onPress={onPressIcon}
>
<Ionicons
name={isSecure ? "eye-off-sharp" : "eye-sharp"}
color={secureIconColor}
size={constants.vw(25)}
/>
</TouchableOpacity>
:
null
}
</View>
</View>
)
}

2-现在是我想更改裁判的部分在该字段中,我创建密码的文本输入字段,并确认要更改的位置我的焦点

const passwordRef = useRef(null);
const confirmPasswordRef = 
useRef(null);

const onSubmitEditing=()=>{
confirmPasswordRef.current.focus();
}
<View style={{ marginTop: constants.vh(66) }}>
<Components.InputField
placeholder={constants.ConstStrings.setANewPassword}
ref={passwordRef}
onSubmitEditing={()=>onSubmitEditing()}
onChangeText={(text) => setState({
...state,
password: text
})}
/>
</View>
<View style={{ marginTop: constants.vh(20) }}>
<Components.InputField
ref={confirmPasswordRef}
placeholder={constants.ConstStrings.confirmPassword}
onChangeText={(text) => setState({
...state,
confirm_password: text
})}
/>
</View>

此部分是结束部分qwertyuiopsdf;';dsyuiopoiuteweryuiopoytreep

代码的问题是,您创建了一个自定义输入组件,但没有向它提供如何处理不同方法的说明。

因此,在您的情况下,通用Input组件知道focus是什么方法,但您的自定义组件不知道。

你应该做什么:

  1. 使您的输入组件成为forwardRef组件,这样您就可以将ref传递给它,然后可以对它执行操作
  2. 使用useImperativeHandle,以便可以调用引用的内部方法
  3. 创建一个focusfn,在您的自定义输入中,它基本上会调用引用的focus方法

你不能像现在这样在道具中传递ref,这在React中不起作用。

我想你所有的组件都是功能性的,在这种情况下:

export const InputField = React.forwardRef({
placeholder,
...
}, ref) => { // pass a ref to here, this way you will let React know to associate the ref from external component to an internal ref
const textInput = useRef(null); // Create a ref to pass to your input
useImperativeHandle(ref, () => ({ // To be able to call `focus` from outside using ref
focus,
});
const focus = textInput.current.focus();
return (
<View style={styles.container}>
<TextInput
ref={textInput}
style={styles.input}
...
/>
...
</View>
)
}

然后在你的组件中,你只需要传递一个由useRef创建的新ref,然后你就可以在.中调用focus

告诉我这是否能帮你解决问题!

最新更新