问题:React-Native - TextInput 的每次击键都会关闭键盘
Issue: React-Native - Keyboard closes on each keystroke for TextInput
对此问题的完全免责声明 - 我已经使用 React Native 工作了大约一两周,我怀疑我在没有完全理解原因的情况下遇到了这个问题!
问题:在 TextInput 字段中每次击键时,键盘会自动关闭并且只记录第一次击键。
情况: 我正在使用预定义数组作为 useState 的默认值。根据当前状态使用 .map() 调用 TextInput 字段。 onChangeText() 更新状态以捕获对数组的更改。每次击键都会更新状态。
尝试过的东西:
- Adding/removing .map()
中使用的不同组件的关键
- 将 keyboardShouldPersistTaps='handled' 添加到调用 .map() 的 ScrollView,包括所有其他可用变体
有谁知道是什么导致键盘在每次击键时关闭,以及如何在继续捕获主状态下对 TextInput 字段的更改的同时防止这种情况发生?
下面我正在处理的代码片段(我删除了一些不相关的细节):
import React, { useState } from 'react';
import {
View,
Text,
Button,
TextInput,
SectionList,
SafeAreaView,
TouchableOpacity,
ScrollView,
Modal,
} from 'react-native';
import { Picker} from '@react-native-community/picker';
//import custom components
import { styles, Break } from './MasterStyles';
import { inputData, ingredients } from './inputData';
function addNewLoaf() {
const [ingredientsList, setIngredientsList] = useState(ingredients);
const [selectedLoaf, setSelectedLoaf] = useState('Regular Loaf');
const [flourModalVisibility, setFlourModalVisibility] = useState(false);
const [newLoaf, setNewLoaf] = useState('');
function IngredientsRecorder() {
return (
<View style={styles.ingredientsContainer}>
<View style={{flexDirection: 'column'}}>
<View>
<Text style={styles.metricTitle}>
Volume of Ingredients:
</Text>
</View>
{
ingredientsList.map(e => {
if(e.isVisible && e.ingredient){
return (
<View style={{flexDirection: 'row', alignItems: 'center'}} key={e.id}>
<View style={{flex:2}}>
<Text style={styles.metricText}>{e.name}:</Text>
</View>
<View style={{flex:3}}>
<TextInput
placeholder='amount'
style={styles.inputText}
keyboardType='number-pad'
value={e.amount}
onChangeText={value => ingredientsAmountHandler(value, e.id)}
/>
</View>
<View style={{flex:1}}>
<Text style={styles.ingredientsText}>{e.units}</Text>
</View>
</View>
)
}
})
}
</View>
</View>
)
}
const ingredientsAmountHandler = (text, id) => {
// setAmount(enteredText);
let newArray = [...ingredientsList]
let index = newArray.findIndex(element => element.id === id)
newArray[index].amount = text
setIngredientsList(newArray)
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.page}>
<Text style={styles.titleText}>Add a New Loaf</Text>
<Break />
<View style={{flexDirection: 'row'}}>
<TextInput
placeholder='What would you like to call your loaf?'
style={styles.inputText}
onChangeText={loafNameInputHandler}
value={newLoaf}
/>
<Button title='Create Loaf' color='#342e29' onPress={addNewLoafHandler} />
</View>
<Break />
<ScrollView styles={styles.page} keyboardShouldPersistTaps='handled'>
<LoafSelector />
<FlourSelector />
<IngredientsRecorder />
</ScrollView>
</View>
<Break />
</SafeAreaView>
);
}
export { addNewLoaf }
由于您正在更改列表,所以您的所有输入都将重新呈现。避免这种情况的一种方法是将您当前的编辑文本存储到另一个状态值中,并在提交输入或失去焦点后将其合并到列表中。这是最小的例子:
let defaultTemp={editingIndex:-1,text:''}
let [temp,setTemp] = useState(defaultTemp); //We will store current being edited input's data and index
{
ingredientsList.map((e,i) => {
if(e.isVisible && e.ingredient){
return (
<View style={{flexDirection: 'row', alignItems: 'center'}} key={e.id}>
<View style={{flex:2}}>
<Text style={styles.metricText}>{e.name}:</Text>
</View>
<View style={{flex:3}}>
<TextInput
placeholder='amount'
style={styles.inputText}
keyboardType='number-pad'
value={temp.editingIndex===i?temp.text:e.amount}
//the input got focus
onFocus={()=>setTemp({editingIndex:i,text:e.amount})}
//the input lost focus
onBlur={()=>{
ingredientsAmountHandler(temp.text, e.id)
setTemp(defaultTemp)
}
onChangeText={text => setTemp({text,editingIndex:i})}
/>
</View>
<View style={{flex:1}}>
<Text style={styles.ingredientsText}>{e.units}</Text>
</View>
</View>
)
}
})
}
一个解决方案是在 Input 上使用 onEndEditing 属性。您可以将本地状态与 onChange 道具一起使用,然后一旦用户点击离开/点击完成,就会调用 onEndEditing 函数,您可以将本地状态应用于父状态。
const TextInput = ({ value, onChange }) => {
const [currentValue, setCurrentValue] = useState(`${value}`);
return (
<Input
value={currentValue}
onChangeText={v => setCurrentValue(v)}
onEndEditing={() => onChange(currentValue)}
/>
);
};
这样父 onChange 属性只会在字段更新完成后调用,而不是在每次击键时调用。除非你在做一些花哨的事情,否则这很好用。
在我的例子中,使用 FieldArray redux-form。
我为 TextInput 添加了超时。
const [displayText, setDisplayText] = useState(input.value && input.value.toString());
const timerRef = useRef(null);
const handleChange = text => {
setDisplayText(text);
if (isDelayOnChangeNeeded) {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
input && input.onChange(text);
}, 1500);
} else {
input && input.onChange(text);
}
};
将 onChangeText 替换为 onEndEditing
onEndEditing={(bidAmts) => setBidAmt(bidAmts)}
而不是
onChangeText={(bidAmts) => setBidAmt(bidAmts)}
const [userName, setUserName] = useState(null);
....
function UserNameTextView() {
return (
<View>
<TextInput
style={styles.textFieldContainer}
placeholder="username"
onChangeText={text => setUserName(text)}
// removed below value prop
value={userName}
/>
</View>
);
}
例如,在上面的代码中,键盘在每次击键时都会消失。这背后的原因是默认情况下,我们在 TextInput 中键入的任何内容都将保留在该字段中,无需将其分配给值 属性(就像我在上面的代码中所做的那样),这会导致视图 re-render 并关闭键盘。删除 value 属性,它将按预期工作。
对此问题的完全免责声明 - 我已经使用 React Native 工作了大约一两周,我怀疑我在没有完全理解原因的情况下遇到了这个问题!
问题:在 TextInput 字段中每次击键时,键盘会自动关闭并且只记录第一次击键。
情况: 我正在使用预定义数组作为 useState 的默认值。根据当前状态使用 .map() 调用 TextInput 字段。 onChangeText() 更新状态以捕获对数组的更改。每次击键都会更新状态。
尝试过的东西:
- Adding/removing .map() 中使用的不同组件的关键
- 将 keyboardShouldPersistTaps='handled' 添加到调用 .map() 的 ScrollView,包括所有其他可用变体
有谁知道是什么导致键盘在每次击键时关闭,以及如何在继续捕获主状态下对 TextInput 字段的更改的同时防止这种情况发生?
下面我正在处理的代码片段(我删除了一些不相关的细节):
import React, { useState } from 'react';
import {
View,
Text,
Button,
TextInput,
SectionList,
SafeAreaView,
TouchableOpacity,
ScrollView,
Modal,
} from 'react-native';
import { Picker} from '@react-native-community/picker';
//import custom components
import { styles, Break } from './MasterStyles';
import { inputData, ingredients } from './inputData';
function addNewLoaf() {
const [ingredientsList, setIngredientsList] = useState(ingredients);
const [selectedLoaf, setSelectedLoaf] = useState('Regular Loaf');
const [flourModalVisibility, setFlourModalVisibility] = useState(false);
const [newLoaf, setNewLoaf] = useState('');
function IngredientsRecorder() {
return (
<View style={styles.ingredientsContainer}>
<View style={{flexDirection: 'column'}}>
<View>
<Text style={styles.metricTitle}>
Volume of Ingredients:
</Text>
</View>
{
ingredientsList.map(e => {
if(e.isVisible && e.ingredient){
return (
<View style={{flexDirection: 'row', alignItems: 'center'}} key={e.id}>
<View style={{flex:2}}>
<Text style={styles.metricText}>{e.name}:</Text>
</View>
<View style={{flex:3}}>
<TextInput
placeholder='amount'
style={styles.inputText}
keyboardType='number-pad'
value={e.amount}
onChangeText={value => ingredientsAmountHandler(value, e.id)}
/>
</View>
<View style={{flex:1}}>
<Text style={styles.ingredientsText}>{e.units}</Text>
</View>
</View>
)
}
})
}
</View>
</View>
)
}
const ingredientsAmountHandler = (text, id) => {
// setAmount(enteredText);
let newArray = [...ingredientsList]
let index = newArray.findIndex(element => element.id === id)
newArray[index].amount = text
setIngredientsList(newArray)
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.page}>
<Text style={styles.titleText}>Add a New Loaf</Text>
<Break />
<View style={{flexDirection: 'row'}}>
<TextInput
placeholder='What would you like to call your loaf?'
style={styles.inputText}
onChangeText={loafNameInputHandler}
value={newLoaf}
/>
<Button title='Create Loaf' color='#342e29' onPress={addNewLoafHandler} />
</View>
<Break />
<ScrollView styles={styles.page} keyboardShouldPersistTaps='handled'>
<LoafSelector />
<FlourSelector />
<IngredientsRecorder />
</ScrollView>
</View>
<Break />
</SafeAreaView>
);
}
export { addNewLoaf }
由于您正在更改列表,所以您的所有输入都将重新呈现。避免这种情况的一种方法是将您当前的编辑文本存储到另一个状态值中,并在提交输入或失去焦点后将其合并到列表中。这是最小的例子:
let defaultTemp={editingIndex:-1,text:''}
let [temp,setTemp] = useState(defaultTemp); //We will store current being edited input's data and index
{
ingredientsList.map((e,i) => {
if(e.isVisible && e.ingredient){
return (
<View style={{flexDirection: 'row', alignItems: 'center'}} key={e.id}>
<View style={{flex:2}}>
<Text style={styles.metricText}>{e.name}:</Text>
</View>
<View style={{flex:3}}>
<TextInput
placeholder='amount'
style={styles.inputText}
keyboardType='number-pad'
value={temp.editingIndex===i?temp.text:e.amount}
//the input got focus
onFocus={()=>setTemp({editingIndex:i,text:e.amount})}
//the input lost focus
onBlur={()=>{
ingredientsAmountHandler(temp.text, e.id)
setTemp(defaultTemp)
}
onChangeText={text => setTemp({text,editingIndex:i})}
/>
</View>
<View style={{flex:1}}>
<Text style={styles.ingredientsText}>{e.units}</Text>
</View>
</View>
)
}
})
}
一个解决方案是在 Input 上使用 onEndEditing 属性。您可以将本地状态与 onChange 道具一起使用,然后一旦用户点击离开/点击完成,就会调用 onEndEditing 函数,您可以将本地状态应用于父状态。
const TextInput = ({ value, onChange }) => {
const [currentValue, setCurrentValue] = useState(`${value}`);
return (
<Input
value={currentValue}
onChangeText={v => setCurrentValue(v)}
onEndEditing={() => onChange(currentValue)}
/>
);
};
这样父 onChange 属性只会在字段更新完成后调用,而不是在每次击键时调用。除非你在做一些花哨的事情,否则这很好用。
在我的例子中,使用 FieldArray redux-form。
我为 TextInput 添加了超时。
const [displayText, setDisplayText] = useState(input.value && input.value.toString());
const timerRef = useRef(null);
const handleChange = text => {
setDisplayText(text);
if (isDelayOnChangeNeeded) {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
input && input.onChange(text);
}, 1500);
} else {
input && input.onChange(text);
}
};
将 onChangeText 替换为 onEndEditing
onEndEditing={(bidAmts) => setBidAmt(bidAmts)}
而不是
onChangeText={(bidAmts) => setBidAmt(bidAmts)}
const [userName, setUserName] = useState(null);
....
function UserNameTextView() {
return (
<View>
<TextInput
style={styles.textFieldContainer}
placeholder="username"
onChangeText={text => setUserName(text)}
// removed below value prop
value={userName}
/>
</View>
);
}
例如,在上面的代码中,键盘在每次击键时都会消失。这背后的原因是默认情况下,我们在 TextInput 中键入的任何内容都将保留在该字段中,无需将其分配给值 属性(就像我在上面的代码中所做的那样),这会导致视图 re-render 并关闭键盘。删除 value 属性,它将按预期工作。