您需要将您的私人标签分成另一个组件:
mainTabs.tsx
const MainTabs: React.FC = () => {
return (
<IonTabs>
<IonRouterOutlet>
<Redirect exact path="/" to="/profile" />
<Route path="/profile" render={() => <Profile />} exact={true} />
<Route path="history" render={() => <History />} exact={true} />
</IonRouterOutlet>
<IonTabBar slot="bottom">
<IonTabButton tab="profile" href="/profile">
<IonIcon icon={personCircleOutline} />
<IonLabel>Profile</IonLabel>
</IonTabButton>
<IonTabButton tab="history" href="/history">
<IonIcon icon={documentTextOutline} />
<IonLabel>History</IonLabel>
</IonTabButton>
</IonTabBar>
</IonTabs>
);
};
export default MainTabs;
之后,您可以在App.tsx中创建一个路由,如果用户登录,您可以在其中有条件地呈现私有选项卡。否则,将呈现登录页面:
应用程序.tsx
return (
<IonApp>
<IonReactRouter>
<Route path="/login" component={Login} exact={true} />
<Route path="/" component={isLoggedIn ? MainTabs : Login} />
</IonReactRouter>
</IonApp>
);
在这一点上,你想要某种状态管理设置(Redux,通过 React hooks 自定义状态管理等),因为你需要isLoggedIn在 App 组件中拥有你的状态,但从 Login 组件中修改它(这真的很混乱)仅快速使用props)。
所以作为一个简单的例子(你绝对可以做得更好),我创建了一个简单的user上下文,我在其中注入了更新isLoggedIn状态的函数:
应用程序.tsx
interface IUserManager {
setIsLoggedIn: Function;
}
const user: IUserManager = {
setIsLoggedIn: () => {}
};
export const UserContext = React.createContext<IUserManager>(user);
const IonicApp: React.FC = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const user = useContext(UserContext);
user.setIsLoggedIn = setIsLoggedIn;
return (
<IonApp>
<IonReactRouter>
<Route path="/login" component={Login} exact={true} />
<Route path="/" component={isLoggedIn ? MainTabs : Login} />
</IonReactRouter>
</IonApp>
);
};
const App: React.FC = () => {
return (
<UserContext.Provider value={user}>
<IonicApp />
</UserContext.Provider>
);
};
我还需要创建一个顶级App组件,以便我可以提供上下文并立即在IonApp组件内部使用它。之后,我可以简单地使用组件user内的上下文Login并在登录时更新状态:
const user = useContext(UserContext);
const loginClick = () => {
if (userName === "a" && password === "a") {
user.setIsLoggedIn(true);
}
};
这是你的分叉演示。