是否有必要在TextInput中设置值属性



我遇到了这样的问题(特别是在TextInput值属性中(:

const Stuff = props => {
const [items, setItems] = useState([]);
const handleNewItem = () => {
setItems([...items, '']);
};
const handleText = (text, index) => {
items[index] = text;
setItems(items);
// this was populating correctly in console.log
// as I type, it will come out like ["somedata", "blah"....] etc...
};
return (
<>
<View style={{marginTop: 20}}>
<View>
{items.map((items, index) => {
return (
<View key={index}>
<Text>{index + 1}</Text>
// issue with setting value attribute
// Text would disappear as I type in the input field
<TextInput value={items} onChangeText={text => handleText(text, index)} />
</View>
);
})}
<TouchableOpacity onPress={e => handleNewItem(e)}>
<Text>Add item</Text>
</TouchableOpacity>
</View>
</View>
</>
);
};

我可以让控制台注销items的正确值,但在我的移动模拟器上,当我键入一些内容时,文本就会消失。

当我从TextInput组件中删除value={items}时,我可以在模拟器输入字段中键入,而不会使文本消失。我一直认为我们需要reactjs的值。我们不需要这个吗?还是我做错了什么?

我建议不要直接更新您的状态。相反,使用新对象来更新状态,如


const handleText = (text, index) => {
let newItems = [...items];
newItems[index] = text;
setItems(newItems);
};

最新更新