我正在尝试通过传递 TextInput (onChangeText) 的值来更新 useState() 数组。该代码工作正常,但是每当我点击 onPress (addBook 函数)时,它都会更新/添加数组中的先前文本而不是当前文本。因此,要添加当前文本,我必须单击两次按钮,这会在我的数组中创建重复项。
我可能会犯非常愚蠢的错误,但找不到。任何人都可以帮助。下面是我的全部代码。
import React, { useState } from "react";
import { TextInput, View, Dimensions, TouchableOpacity } from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { Entypo } from "@expo/vector-icons";
const screenHeight = Math.round(Dimensions.get("window").height);
const AddBookName = ({ hidePressed }) => {
const [book, setBook] = useState();
const [bookList, setBookList] = useState(["no name"]);
const addBook = () => {
setBookList([...bookList, book]);
console.log(bookList);
};
return (
<View style={{ flexDirection: "row" }}>
<View style={{ flex: 1 }}>
<TextInput
style={{
fontSize: 20,
paddingVertical: 10,
backgroundColor: "#ececec",
paddingLeft: 10,
}}
placeholder="Enter the Book Name"
placeholderTextColor="grey"
// value={book}
onChangeText={(text) => setBook(text)}
type="text"
></TextInput>
</View>
<TouchableOpacity
style={{
flex: 0.15,
backgroundColor: "green",
alignItems: "center",
justifyContent: "center",
}}
onPress={() => addBook()}
>
<View>
<MaterialCommunityIcons name="check" size={24} color="white" />
</View>
</TouchableOpacity>
<TouchableOpacity
style={{
flex: 0.15,
backgroundColor: "red",
alignItems: "center",
justifyContent: "center",
}}
onPress={hidePressed}
>
<View>
<Entypo name="cross" size={24} color="white" />
</View>
</TouchableOpacity>
</View>
);
};
export default AddBookName;