我有以下组件,它应该根据按钮单击加载另外两个组件。
当我单击"地下城页面"链接时,我的GameDungeon组件应该加载,并且它还应该隐藏"GameCharacter"组件。
同样,但"字符页"按钮颠倒了。
但是,当我单击任一按钮时,没有任何反应。 没有变化,没有加载,也没有错误。
所以我不确定从这里开始。
我遵循了一些 React 和 React Hooks 教程,但我就是无法让它工作。
这是我的代码:
import React, { useState } from "react";
import GameDungeon from "../App";
import GameCharacter from "../Character/App";
const Admin = () => {
const [showDungeon, setDungeon] = useState(false);
const [showCharacter, setCharacter] = useState(false);
const handleCharacterClick = e => { setDungeon(false) && setCharacter(true) };
const handleDungeonClick = e => { setCharacter(false) && setDungeon(true) };
return (
<div className="admin">
<nav>
<div>
<ul>
<li>
<a id="DungeonPage" href="#" onClick={ () => handleDungeonClick}>Game Dungeon</a>
</li>
<li>
<a id="CharacterPage" href="#" onClick={ () => handleCharacterClick}>Game Character</a>
</li>
</ul>
</div>
</nav>
<div>
{showDungeon && <GameDungeon />}
</div>
<div>
{showCharacter && <GameCharacter />}
</div>
</div>
);
}
我错过了什么或做错了什么吗?
谢谢!
你必须直接将回调函数作为 prop 传递。此外,使用useCallback
钩子包装回调以获得更好的性能。
import React, { useState, useCallback } from "react";
import GameDungeon from "../App";
import GameCharacter from "../Character/App";
const Admin = () => {
const [showDungeon, setDungeon] = useState(false);
const [showCharacter, setCharacter] = useState(false);
const handleCharacterClick = useCallback(e => setDungeon(false) || setCharacter(true));
const handleDungeonClick = useCallback(e => setCharacter(false) || setDungeon(true));
return (
<div className="admin">
<nav>
<div>
<ul>
<li>
<a id="DungeonPage" href="#" onClick={handleDungeonClick}>Game Dungeon</a>
</li>
<li>
<a id="CharacterPage" href="#" onClick={handleCharacterClick}>Game Character</a>
</li>
</ul>
</div>
</nav>
<div>
{showDungeon && <GameDungeon />}
</div>
<div>
{showCharacter && <GameCharacter />}
</div>
</div>
);
}
你的代码有几个问题。要解决此问题,您可以进行以下更改:
import React, { useState } from "react";
import GameDungeon from "../App";
import GameCharacter from "../Character/App";
function Admin(){
const [showDungeon, setDungeon] = useState(false);
const [showCharacter, setCharacter] = useState(false);
function handleCharacterClick(){
setDungeon(false);
setCharacter(true);
}
function handleDungeonClick() {
setCharacter(false);
setDungeon(true);
}
return (
<div className="admin">
<nav>
<div>
<ul>
<li>
<a id="DungeonPage" href="#" onClick={handleDungeonClick}>Game Dungeon</a>
</li>
<li>
<a id="CharacterPage" href="#" onClick={handleCharacterClick}>Game Character</a>
</li>
</ul>
</div>
</nav>
<div>
{!!showDungeon && <GameDungeon />}
</div>
<div>
{!!showCharacter && <GameCharacter />}
</div>
</div>
);
}