在每个按钮中,您使用两个不同的事件onClick 和onMouseDown处理点击
通过创建对象数组检查序列是否正确,每个对象将是一个具有唯一 ID 的按钮。您需要计算真正点击按钮的数量。
我们需要使用react 而不是Javascript BOM 重新启动游戏,将buttons 和count 设置为其初始状态将重置游戏。
这是完整的工作代码
import "./styles.css";
import React, { useState } from "react";
// We need to loop over this array to render buttons and answeres
// Id : to handle click on target button
// isRight : weather the answer is right or wrong
// clicked: weather button clicked or not
const initialState = [
{ id: 1, isRight: true, label: "True 1", clicked: false },
{ id: 2, isRight: true, label: "True 2", clicked: false },
{ id: 3, isRight: true, label: "True 3", clicked: false },
{ id: 4, isRight: true, label: "True 4", clicked: false },
{ id: 5, isRight: true, label: "True 5", clicked: false },
{ id: 6, isRight: true, label: "True 6", clicked: false },
{ id: 7, isRight: false, label: "False 7", clicked: false },
{ id: 8, isRight: false, label: "False 8", clicked: false }
];
export default function App() {
// Button Restart refresh Page
// reset counter and count to their inital states will reset the game
function resetGame() {
setButtons(initialState);
setCount(6);
setCorrect(null);
}
const [buttons, setButtons] = useState(initialState);
// Counter
const [count, setCount] = useState(6);
const [correct, setCorrect] = useState(null);
// Click handler will handle both count and buttons changes
const buttonClickHandler = (id) => {
if (count === 0) {
return;
}
setCount(count - 1);
// Update an array of objects
setButtons(
buttons.map((item) =>
item.id === id ? { ...item, clicked: !item.clicked } : item
)
);
};
// We are counting the clicked buttons which have a property isRight : true
const checkIfCorrect = () => {
let correct = buttons.filter(
(item) => item.clicked === true && item.isRight === true
).length;
if (correct === 6) {
setCorrect(true)
} else {
setCorrect(false)
}
};
return (
<div className="App">
<div>
<button onClick={resetGame} refresh="true">
RestartNew
</button>
<h3>Chances: 6</h3>
{count}
</div>
<div>
<h2>Answers</h2>
{buttons.map(
(button) =>
button.clicked && <button key={button.id}>{button.label}</button>
)}
</div>
<h2>Buttons Questions!</h2>
{/* Question buttons */}
{buttons.map((button) => (
<button key={button.id} onClick={() => buttonClickHandler(button.id)}>
{button.label}
</button>
))}
<br />
<br />
<h2>Checker</h2>
<button onClick={() => checkIfCorrect()}>Check Answers</button>
<br />
<br />
// Check correct and render your components
{correct != null && correct && <div>correct</div>}
{correct != null && !correct && <div>Wrong</div>}
</div>
);
}
Working Demo
对不起我的英语不好^_^