我想让按钮打印出来,每当它被点击改变属性搜索游戏到相反(如果它的假-真),并打印出另一个按钮。现在甚至没有一个按钮出现(如果它在jsx代码返回后,它打印按钮,但不改变它的点击)。知道怎么写下来吗?
let searchingGame = false;
const isSearchingForGame = () => {
searchingGame = !searchingGame;
if (isSearchingForGame == true)
{
return (<button onClick={isSearchingForGame} className="find-match">Find Match</button>)
}
else
{
return (<button onClick={isSearchingForGame} className="find-match">Searching for a Match</button>)
}
}
return (
<div className="look-ranked-container">
<div className="time-searching">Searching: 00:23 min</div>
{isSearchingForGame}
</div>
)
}
- 函数未调用,改为:
{isSearchingForGame()}
searchingGame
应该是一个钩子(例如useState
)- 双
return
可以通过设置text
然后单一返回 来简化。
演示:
const { useState, useEffect } = React;
function App() {
const [searchingGame, setSearchingGame] = useState(false);
const toggleIsSearching = () => setSearchingGame(!searchingGame);
const getContent = () => {
const text = (searchingGame)
? 'Find Match'
: 'Searching for a Match'
return (<button onClick={toggleIsSearching} className="find-match">{text}</button>)
}
return (
<div className="look-ranked-container">
<div className="time-searching">Searching: 00:23 min</div>
{getContent()}
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("react"));
root.render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="react"></div>
你应该像{isSearchingForGame()}那样调用函数isSearchingForGame并在你的组件中用useState将变量searchingGame设置为一个状态.
此外,您可以通过在jsx代码中添加函数的代码片段来改进这段代码,如下所示:return (
<div className="look-ranked-container">
<div className="time-searching">Searching: 00:23 min</div>
<button onClick={isSearchingForGame} className="find-match">.
{ searchingGame ? 'Find Match' : 'Searching for a Match' }</button>
</div>
)