我在 React 应用程序的子组件中模拟保存按钮上的单击事件时遇到问题。
我有一个名为 AddQuestionsPage 的父组件,我在其中渲染名为 Question 的子组件的多个实例。每个问题组件都包含一个输入字段和一个用于保存问题的保存按钮。
我的目标是当用户单击 AddQuestionsPage 组件中的“完成测验”按钮时,触发每个问题组件的保存按钮上的单击事件。
我尝试使用 refs 访问问题组件中的保存按钮并模拟单击事件,但它似乎没有按预期工作。点击事件没有被触发,问题也没有被保存。
我已经验证参考是否已正确分配给保存按钮,但由于某种原因,当我在handleSaveAllQuestions函数中调用buttonRef.current?.click()时,单击事件没有被触发。
// AddQuestionsPage component
// Renders multiple Question components
// Handles saving questions
// Should trigger save button clicks on child Question components
function AddQuestionsPage() {
const saveButtonRefs = useRef([]);
const handleSaveAllQuestions = async () => {
try {
await Promise.all(
saveButtonRefs.current.map(async (buttonRef) => {
await buttonRef.current?.click();
})
);
} catch (error) {
console.error("Error saving questions:", error);
}
};
const handleFinishQuiz = async () => {
try {
await handleSaveAllQuestions();
console.log("Quiz finished");
} catch (error) {
console.error("Error finishing quiz:", error);
}
};
return (
<div>
{/* Render multiple Question components */}
{questions.map((question, index) => (
<Question
key={index}
saveButtonRef={(ref) => (saveButtonRefs.current[index] = ref)}
/>
))}
<button onClick={handleFinishQuiz}>Finish Quiz</button>
</div>
);
}
// Question component
// Contains an input field and a save button
// Should save the question when the save button is clicked
function Question({ saveButtonRef }) {
const handleSaveQuestion = async () => {
try {
// Save the question logic...
} catch (error) {
console.error("Error saving question:", error);
}
};
return (
<div>
<input type="text" />
<button ref={saveButtonRef} onClick={handleSaveQuestion}>
Save
</button>
</div>
);
}
我已检查错误并确保所有组件均正确呈现并正常运行。关于 refs 和 click 事件在 React 中的工作方式,我是否遗漏或误解了某些内容?
任何帮助或见解将不胜感激。预先感谢!