【发布时间】:2020-08-25 06:46:33
【问题描述】:
对此的完全免责声明 - 我已经使用 react native 大约一两个星期了,我怀疑我遇到了这个问题而没有完全理解为什么!
问题:在 TextInput 字段中的每次击键时,键盘都会自动关闭并且只记录第一次击键。
情况:我使用预定义数组作为 useState 的默认值。基于当前状态使用 .map() 调用 TextInput 字段。 onChangeText() 更新状态以捕获对数组的更改。每次击键都会更新状态。
尝试过的事情:
- 为 .map() 中使用的不同组件添加/删除 Key
- 将 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 }
【问题讨论】:
标签: reactjs react-native keyboard array.prototype.map