focus next textInput in react native in functional component



我有一个textinput组件

return (
<TextInput
onChangeText={(text) => {
props.onChange(text)
}}
value={props.value}
placeholder={props.placeholder}
placeholderTextColor={Colors.gry}
autoFocus={props.focus ? true : false}
onFocus={() => setColor(Colors.org)}
onBlur={() => setColor(Colors.gry)}
ref={props.ref}
returnKeyType='next'
/>
)

我像这样使用这个组件

const inputRef = useRef<any>()
<Input
keyboard={'numeric'}
onChange={(text) => {
setOtp({ ...otp, o1: text })
inputRef.current.focus()
}}
value={otp.o1}
max={1}
/>
</View>
<View style={styles.input}>
<Input
keyboard={'numeric'}
onChange={(text) => setOtp({ ...otp, o2: text })}
value={otp.o2}
ref={inputRef}
max={1}
/>
</View>

我想在第一个输入字段更改文本时关注下一个输入字段我该怎么做呢?

由于您的组件Input是您需要使用的TextInput的包装器forwardRef传递ref给内部子元素,而不是直接通过props

下面是react文档中的一段代码片段,告诉你如何做

const Input = React.forwardRef((props, ref) => (
<TextInput
onChangeText={(text) => {
props.onChange(text)
}}
value={props.value}
placeholder={props.placeholder}
placeholderTextColor={Colors.gry}
autoFocus={props.focus ? true : false}
onFocus={() => setColor(Colors.org)}
onBlur={() => setColor(Colors.gry)}
ref={ref} 
returnKeyType='next'
/>)
// You can now get a ref directly :
const inputRef = React.createRef();
<Input
keyboard={'numeric'}
onChange={(text) => setOtp({ ...otp, o2: text })}
value={otp.o2}
ref={inputRef}
max={1}

那么你可以使用focus

最新更新