繁体   English   中英

在组件之间共享 state

[英]Share state between components

我正在开发一个爱好健身房管理应用程序,我对在 React-Native 中的三个组件之间共享 state 的机制感到困惑。

我的三个组成部分是:

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 boolean 变量的内容在(2.)FlatListDATA_AEROBICDATA_KIDS arrays 道具之间交替。

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 boolean 变量链接到SwitchButton组件(3.)的 state ,以及如何使其打开和关闭。

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

非常感谢!

我认为您只需要“价值”就可以接受在开关按钮上传递给它的道具。 然后,无论您使用开关按钮,只需将 boolean 值从 state 传递给它,例如

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

As for setting state 'globally' so this.state.switchEnabled can be updated from various places / accessible all over the app you need to look into state management tools like Redux (or I hear 'React Hooks' is now a thing and preferred. ...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM