使用状态导航到另一个 React 组件

Using state to navigate to another React component

我有一个用于显示游戏的简单 React 应用程序。

它在页面顶部有 3 个按钮,用于控制用户单击时可以转到的位置,如下所示:

[Games]   |   [Create]    |    [Login]

对于我的 GamesList.js、CreateGame.js 和 LoginForm.js 组件。

导航可以像这样使用 React hooks 简单地控制:

// *** GamerPagesNavigation.js

const [showGames, setGames] = useState(true);
const [showCreate, setCreate] = useState(false);
const [showLogin, setLogin] = useState(false);


const handleGamesClick = useCallback(e => { (setCreate(false) || setLogin(false) ) || setGames(true) });
const handleCreateClick = useCallback(e => { (setGames(false) || setLogin(false) ) || setCreate(true) });
const handleLoginClick = useCallback(e => { (setCreate(false) || setGames(false) ) || setLogin(true) });

<div>
    {showGames && <GamesList />}
</div>
<div>
    {showCreate && <CreateGame />}
</div>
<div>
    {showLogin && <LoginForm />}
</div>

而且效果非常好! :)

太棒了!

但是现在,我的 LoginForm.js 组件上有一个用于登录的按钮。

提交并通过身份验证后,我希望将用户定向到登录页面。

但我不知道如何从 LoginForm.js 组件转到 CreateGame 组件。

因为我的状态是在 GamerPagesNavigation.js 组件中控制的,所以我不知道如何在另一个组件中获取状态值。

当我在我的 LoginForm.js 组件中尝试这个时,它说 showCreate 是未定义的:

setCreate(true)

我明白了,因为它是在不同的 React 组件文件中定义的。

那么有办法做到这一点吗?

谢谢! :)

通过 props 传递函数

    <LoginForm onLogin={() => setCreate(true)} />

来自LoginForm.js

需要时调用props.onLogin()

const [showGames, setGames] = useState(true);
const [showCreate, setCreate] = useState(false);
const [showLogin, setLogin] = useState(false);


const handleGamesClick = useCallback(e => { (setCreate(false) || setLogin(false) ) || setGames(true) });
const handleCreateClick = useCallback(e => { (setGames(false) || setLogin(false) ) || setCreate(true) });
const handleLoginClick = useCallback(e => { (setCreate(false) || setGames(false) ) || setLogin(true) });

<div>
    {showGames && <GamesList />}
</div>
<div>
    {showCreate && <CreateGame />}
</div>
<div>
    {showLogin && <LoginForm handleCreateClick={handleCreateClick}/>}
</div>

然后在 LoginForm 中解构它

const LoginForm = (props)=>{
 const {handleCreateClick}= props;
 const handleSubmit=()=>{
 // your form submission logic
 handleCreateClick()
}
return(
<form onSubmit={handleSubmit}>
//your form inputs 
</form>
)
}