我创建了一个带有来自 cli 的 tabs starter 模板的 ionic react 应用程序,并将登录功能添加到现有结构中。
我做了什么 :
应用程序.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
最佳答案
您需要将您的私有(private)标签分成另一个组件:
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 中创建一个路由,如果用户登录,您可以在其中有条件地呈现私有(private)选项卡。否则,将呈现登录页面:
应用程序.tsx
return (
<IonApp>
<IonReactRouter>
<Route path="/login" component={Login} exact={true} />
<Route path="/" component={isLoggedIn ? MainTabs : Login} />
</IonReactRouter>
</IonApp>
);
此时,您想要某种状态管理设置(Redux、通过 React 钩子(Hook)自定义状态管理等),因为您需要拥有
isLoggedIn
状态在 App 组件中,但从 Login 组件中修改它(仅使用 props 会很快变得困惑)。所以作为一个简单的例子(你绝对可以做得更好),我创建了一个简单的
user
上下文,我在其中注入(inject)更新 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);
}
};
这是你的 fork demo .
关于reactjs - 在 Ionic React 中隐藏登录屏幕上的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62359500/