我使用 Ionic 5 选项卡模板创建了一个 Ionic React 应用程序。
我想将一个对象从应用程序组件传递到选项卡组件。
有什么办法可以做到吗?
Tab1 和 Tab2 是我的选项卡组件。
Note:我希望这个对象在两个选项卡组件中使用两种方式的数据绑定,即每当该对象在一个选项卡组件中更改时,它必须在第二个选项卡组件中更新。我想在不使用 Redux 或任何第三方库的情况下实现它。
我的应用程序组件如下所示:
<IonApp>
<IonReactRouter>
<IonTabs>
<IonRouterOutlet>
<Route path="/tab1"
component=Tab1
exact={true} />
<Route path="/tab2"
component=Tab2
exact={true} />
<Route path="/" render={() => <Redirect to="/tab1" />} exact={true} />
</IonRouterOutlet>
<IonTabBar slot="bottom">
<IonTabButton tab={"Title1"} href={"/tab1"}>
<IonIcon icon={settings} />
<IonLabel>{"Title1"}</IonLabel>
</IonTabButton>
<IonTabButton tab={"Title2"} href={"/tab2"}>
<IonIcon icon={settings} />
<IonLabel>{"Title2"}</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
</IonReactRouter>
</IonApp>
您可以使用React.Context使用 React Hooks 在选项卡之间进行简单的状态交互,然后您可以向上移动到React.useReducer
下面是一个使用的基本示例React.Context
- CodeSandbox.io 上的示例
import React from "react";
// create the context
export const Context = React.createContext();
// create the context provider, we are using use state to ensure that
// we get reactive values from the context...
export const TheProvider = ({ children }) => {
// the reactive values
const [sharedValue, setSharedValue] = React.useState("initial");
// the store object
let state = {
sharedValue,
setSharedValue
};
// wrap the application inthe provider with the initialized context
return <Context.Provider value={state}>{children}</Context.Provider>;
};
export default Context;
将应用程序包装在提供者中
import { TheProvider } from "./some-context";
const App: React.FC = () => {
return (
<IonApp>
<TheProvider>
{/* here the provider wraps the whole application to allow */}
{/* access to the context that is defined */}
<IonReactRouter>
<IonTabs>
<Route
path="/"
render={() => <Redirect to="/tab1" />}
exact={true}
/>
<IonRouterOutlet>
<Route path="/tab1" component={Tab1} exact={true} />
<Route path="/tab2" component={Tab2} exact={true} />
</IonRouterOutlet>
<IonTabBar slot="bottom">
<IonTabButton tab={"Title1"} href={"/tab1"}>
<IonLabel>{"Title1"}</IonLabel>
</IonTabButton>
<IonTabButton tab={"Title2"} href={"/tab2"}>
<IonLabel>{"Title2"}</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
</IonReactRouter>
</TheProvider>
</IonApp>
);
};
现在是一个在选项卡中使用的示例
const Tab2 = () => {
// use react hooks to get the context and the information that is stored
// in the context, the value and the function to modify the value
const { sharedValue, setSharedValue } = React.useContext(AppContext);
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>TAB ONE</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<>
<h2>TAB TWO</h2>
<div>{sharedValue}</div>
<IonButton
onClick={() =>
setSharedValue("From Tab 2: " + new Date().getMilliseconds())
}
>
Update Value
</IonButton>
</>
</IonContent>
</IonPage>
);
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)