我正在构建一个 react-native 应用程序并在我的应用程序中使用 react-native-tab-view。
我的屏幕有两个选项卡,每个选项卡都有一个文本字段。
状态为MyScreen
,我将state
andsetState
作为道具传递给选项卡。
我添加useEffect
了在状态更改时记录状态,当我在子选项卡上的两个字段中的任何一个中键入文本时,状态会正确更新。
屏幕在导航栏的标题右侧添加了一个保存按钮。
我的问题是状态已更新,但是当我单击保存时,它似乎被设置回初始值,因为日志在saveState
函数中显示;
请指教。
import React, { useState, useEffect, useContext } from "react";
import { StyleSheet, View, Dimensions, TextInput, ScrollView, TouchableOpacity, Picker, Switch } from "react-native";
import { TabView, TabBar } from "react-native-tab-view";
import DateTimePicker from "@react-native-community/datetimepicker";
const Tab1 = ({ navigation, state, setState }) => {
return (
<View style={styles.scene}>
<ScrollView>
<SansBoldText style={styles.label}>First</SansBoldText>
<TextInput style={styles.field} value={state.first} onChangeText={(text) => setState((prevState) => ({ ...prevState, first: text }))} />
</ScrollView>
</View>
);
};
const Tab2 = ({ navigation, state, setState }) => {
return (
<View style={styles.scene}>
<ScrollView>
<SansBoldText style={styles.label}>Second</SansBoldText>
<TextInput style={styles.field} value={state.second} onChangeText={(text) => setState((prevState) => ({ ...prevState, second: text }))} />
</ScrollView>
</View>
);
};
const initialLayout = { width: Dimensions.get("window").width };
export default function MyScreen({ navigation }) {
const [index, setIndex] = useState(0);
const [routes] = useState([
{ key: "tab1", title: "Tab1" },
{ key: "tab2", title: "Tab2" },
]);
const [state, setState] = useState({
first: "",
second: "",
});
const saveState = () => {
console.log(state); // this prints the initial state even after it is already changed
};
useEffect(() => {
navigation.setOptions({
headerRight: () => {
return (
<TouchableOpacity activeOpacity={0.5} style={{ paddingRight: 10 }} onPress={saveState}>
<Ionicons name="md-save" size={30} />
</TouchableOpacity>
);
},
});
}, []);
useEffect(() => {
console.log("state changed = ", state);
}, [state]);
const renderScene = ({ route }) => {
switch (route.key) {
case "tab1":
return <Tab1 navigation={navigation} state={state} setState={setState} />;
case "tab2":
return <Tab2 navigation={navigation} state={state} setState={setState} />;
default:
return null;
}
};
const renderTabBar = (props) => <TabBar {...props} indicatorStyle={{ backgroundColor: "black" }} style={{ backgroundColor: "#e0e0e0" }} labelStyle={{ color: "#000" }} />;
return <TabView navigationState={{ index, routes }} renderTabBar={renderTabBar} renderScene={renderScene} onIndexChange={setIndex} initialLayout={initialLayout} />;
}