import React, {useRef, useState} from 'react';
import {KeyboardAvoidingView, Platform, ScrollView, TextInput} from 'react-native';
import {SafeAreaView} from "react-native-safe-area-context";
export const ProfileScreen: React.FC = () => {
const [userInfo, setUserInfo] = useState({
name: '',
lastName: '',
});
const scrollViewRef = useRef<ScrollView>(null);
const inputNameRef = useRef<TextInput>(null);
const inputLastNameRef = useRef<TextInput>(null);
...
return (
<SafeAreaView style={{flex: 1}}>
<KeyboardAvoidingView
behavior={(Platform.OS === 'iOS') ? 'padding' : 'height'}
style={{flex: 1}}>
<ScrollView
keyboardShouldPersistTaps={'handled'}
ref={scrollViewRef}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}>
<TextInput
ref={inputNameRef}
placeholder={'Your Name'}
onChangeText={(text) => {
setUserInfo((prevState) => ({...prevState, name: text}));
}}
value={userInfo.name}
onSubmitEditing={inputLastNameRef.current?.focus()}
/>
<TextInput
ref={inputLastNameRef}
placeholder={'Your Last Name'}
onChangeText={(text) => {
setUserInfo((prevState) => ({...prevState, lastName: text}));
}}
value={userInfo.lastName}
/>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
};
当我点击
TextInput
时,键盘会打开。但是,当我按下某个键(触发状态更新)时,它会关闭。我错过了什么?
当我点击 TextInput 时,键盘会打开。但是,当我按下某个键(触发状态更新)时,它会关闭。我错过了什么?
出现此问题是因为 TextInput 的 onSubmitEditing 回调执行不正确。具体来说,您直接在 onSubmitEditing 属性中调用 focus 方法。这会导致该方法在渲染阶段立即被调用,而不是被分配为 onSubmitEditing 事件的回调。因此,它会破坏输入处理行为并导致键盘关闭。
要解决此问题,您需要将 focus 方法调用包装在箭头函数中,以便仅在 onSubmitEditing 事件发生时执行。这是更正后的代码:
import React, {useRef, useState} from 'react';
import {KeyboardAvoidingView, Platform, ScrollView, TextInput} from 'react-native';
import {SafeAreaView} from "react-native-safe-area-context";
export const ProfileScreen: React.FC = () => {
const [userInfo, setUserInfo] = useState({
name: '',
lastName: '',
});
const scrollViewRef = useRef<ScrollView>(null);
const inputNameRef = useRef<TextInput>(null);
const inputLastNameRef = useRef<TextInput>(null);
return (
<SafeAreaView style={{flex: 1}}>
<KeyboardAvoidingView
behavior={(Platform.OS === 'iOS') ? 'padding' : 'height'}
style={{flex: 1}}>
<ScrollView
keyboardShouldPersistTaps={'handled'}
ref={scrollViewRef}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}>
<TextInput
ref={inputNameRef}
placeholder={'Your Name'}
onChangeText={(text) => {
setUserInfo((prevState) => ({...prevState, name: text}));
}}
value={userInfo.name}
onSubmitEditing={() => inputLastNameRef.current?.focus()} // Use arrow function here
/>
<TextInput
ref={inputLastNameRef}
placeholder={'Your Last Name'}
onChangeText={(text) => {
setUserInfo((prevState) => ({...prevState, lastName: text}));
}}
value={userInfo.lastName}
/>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
};