我使用cli中的tabs入门模板创建了离子反应应用程序,并将登录功能添加到现有结构中。
我做了什么:
App.tsx
const App: React.FC = () => (
<IonApp>
<IonReactRouter>
<IonTabs>
<IonRouterOutlet>
<Route path="/profile" component={Profile} exact={true} />
<Route path="/history" component={History} />
<Route path="/login" component={Login} exact={true} />
<Route path="/" component={Login} 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>
</IonReactRouter>
</IonApp>
);
问题是我在登录屏幕上看到了所有选项卡。我希望选项卡仅在用户登录后才显示。
工作演示here
答案 0 :(得分:4)
您需要将您的私人标签划分为另一个组件:
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 中创建一条路由,如果用户已登录,则可以在其中有条件地呈现私有选项卡。否则,将呈现“登录”页面:
App.tsx
return (
<IonApp>
<IonReactRouter>
<Route path="/login" component={Login} exact={true} />
<Route path="/" component={isLoggedIn ? MainTabs : Login} />
</IonReactRouter>
</IonApp>
);
这时,您需要某种状态管理设置(Redux,通过React钩子进行自定义状态管理等),因为您需要在App组件中拥有isLoggedIn
状态,但需要从Login组件(仅使用props即可快速获得混乱)。
作为一个简单的示例(您当然可以做得更好),我创建了一个简单的user
上下文,在其中注入了更新isLoggedIn
状态的函数:
App.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);
}
};
这是您的demo分叉。