在组件之间共享状态

时间:2021-02-16 18:29:55

标签: javascript reactjs react-native react-component

我正在开发一个业余爱好健身房管理应用程序,我对 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;

我希望日程组件中的 SwitchButton 按钮(1.)DATA_AEROBICDATA_KIDS 之间交替根据 listAerobic 布尔变量的内容,在 (2.) 中排列 FlatList 的 props。

2. MondayPage:

[...]
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 中的第一个项目。

非常感谢!

1 个答案:

答案 0 :(得分:0)

我认为您只需要“值”就可以接受在切换按钮上传递给它的道具。然后无论你在哪里使用 switch 按钮,只需从 state 传递一个布尔值到它,例如

<SwitchButton enabled={this.state.switchEnabled}/>

至于设置“全局”状态,因此 this.state.switchEnabled 可以从各个位置更新/在整个应用程序中都可以访问,您需要查看 Redux 等状态管理工具(或者我听说“React Hooks”现在是一回事和首选....)