javascript - 在组件之间共享状态
问题描述
我正在开发一个爱好健身房管理应用程序,我对 React-Native 中三个组件之间共享状态的机制感到困惑。
我的三个组成部分是:
1. 时间表:
[...]
function Schedule() {
return (
<Stack.Navigator
initialRouteName="Monday"
screenOptions={{
headerStyle: { backgroundColor: "#f58220" },
headerTintColor: "#fff",
headerTitleStyle: { fontWeight: "bold" },
headerRight: () => <SwitchButton />,
}}
>
<Stack.Screen
name="TabStack"
component={TabStack}
options={{ title: "Aerobic Schedule" }}
/>
</Stack.Navigator>
);
}
export default Schedule;
我希望我的 Schedule 组件(1.)中的SwitchButton按钮根据listAerobic布尔变量的内容在(2.)中FlatList的DATA_AEROBIC和DATA_KIDS数组道具之间交替。
2. 星期一页面:
[...]
const MondayPage = () => {
const [selectedId, setSelectedId] = useState(null);
const [listAerobic, setListAerobic] = useState(true);
const renderItem = ({ item }) => {
const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#f9c2ff";
return (
<Item
item={item}
onPress={() => setSelectedId(item.id)}
style={{ backgroundColor }}
/>
);
};
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, padding: 5 }}>
<SafeAreaView style={styles.container}>
<FlatList
data={listAerobic ? DATA_AEROBIC : DATA_KIDS}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
</SafeAreaView>
</View>
</SafeAreaView>
);
};
但是,我不知道如何将listAerobic布尔变量链接到SwitchButton组件(3.)的状态,以及如何使其打开和关闭。
3. 开关按钮:
const SwitchButton = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View style={styles.container}>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
<Text> aerobic/kids</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
marginRight: 5,
padding: 5,
}
});
export default SwitchButton;
任何指导都会很棒!我提到我真的试图在不同的教程上查找它,但我似乎无法理解它的要点。这是我在 React/React-Native 中的第一个项目。
非常感谢!
解决方案
我认为您只需要“价值”就可以接受在开关按钮上传递给它的道具。然后,无论您在何处使用切换按钮,只需将一个布尔值从状态传递给它,例如
<SwitchButton enabled={this.state.switchEnabled}/>
至于“全局”设置状态,因此this.state.switchEnabled
可以从各个地方更新/可以在整个应用程序中访问,您需要查看像 Redux 这样的状态管理工具(或者我听说“React Hooks”现在已经成为一种东西并且是首选......)
推荐阅读
- java - 无法使用 wagon maven FTPS 传输中型大文件
- react-native - 是否可以在 MapView 之外重用 react-native-maps 标记?
- excel - 在 Excel VBA 中通过 ActiveCell 突出显示行和列
- webpack - 每个 html 文件都包含它自己的 js 脚本
- java - 确认后一次又一次收到来自Google Pub / Sub订阅的消息[Heisenbug]
- autodesk-forge - Autodesk Forge - Revit New Dimension 添加但不可见
- vue.js - vue-meta 不在页面源代码中显示元标记
- r - 如何在 R 中使用陈述的偏好数据从长到宽
- youtube-api - 从我的 youtube 频道检索我的评论历史记录
- java - 读取文本文件并获取每行长度的问题,如果长度合适,同时将它们添加到字符串中