我正在构建一个 react hooks 应用程序作为一些即将到来的面试的练习,并实际使用这个测验组件来研究对话问题。我有一个对象数组,每个对象包含两条信息:一个问题和一个答案。我正在遍历对象数组以呈现每个对象一个 div。每个 div 包含:一个问题、一个输入(捕获猜测)和三个按钮:提交(评估猜测)、重试(清除/重置输入字段)和显示答案(以防用户不这样做)不知道答案)。
我想重置特定的输入字段及其状态,但没有成功。
感谢您的任何建议!
import QA from './questions-answers';
function Quiz(props) {
const [selectedQuestionId, setSelectedQuestionId] = useState(null);
const [guess, setGuess] = useState();
const [evalGuess, setEvalGuess] = useState(null);
const handleSelectedQuestionId = (id) => {
if (selectedQuestionId === null) {
setSelectedQuestionId(id);
} else {
setSelectedQuestionId(null);
};
};
const handleEvalGuess = (answer, id) => {
let guessArr = guess.toLowerCase().split(' ').sort();
let guessArrUnique = [...new Set(guessArr)];
let ansArr = answer.toLowerCase().split(' ').sort();
let ansArrUnique = [...new Set(ansArr)];
const matches = ansArrUnique.filter(element => guessArrUnique.includes(element));
if (matches > ansArrUnique/2) {
setEvalGuess('great answer');
} else {
setEvalGuess('try again');
};
};
const handleReset = (id) => {
setGuess(null);
setEvalGuess(null);
};
return (
<div className='quiz-component'>
<h1>
Interview Practice Quiz
</h1>
<div className='questions'>
{QA.map((question, index) => (
<div key={index}>
<h3 key={index}>{question.question}</h3>
<input className='question-input spacer-right' onChange={(e) => setGuess(e.target.value)}/>
<button className='med-btn spacer-right' onClick={() => handleEvalGuess(question.answer, index)}>Submit</button>
<button className='med-btn spacer-right' onClick={() => handleReset(index)}>Try Again</button>
<button className='med-btn spacer-right' onClick={() => handleSelectedQuestionId(index)}>Show Answer</button>
<div>
{(selectedQuestionId === index) ? <p>{question.answer}</p> : null}
</div>
<div>
{evalGuess === 'great answer' ? <p>Great answer!</p> : <p></p>}
{evalGuess === 'try again' ? <p>You should try again.</p> : <p></p>}
</div>
</div>
))}
</div>
</div>
);
}