无法触发子组件内保存按钮的点击事件

问题描述 投票:0回答:1

我在 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 中的工作方式,我是否遗漏或误解了某些内容?

任何帮助或见解将不胜感激。预先感谢!

reactjs react-hooks onclick
1个回答
0
投票

React 事件是合成的。它们与本机 JavaScript 事件不同。无法通过触发

handleSaveQuestion
来调用
element.click()
回调。您需要触发实际的回调,而不是尝试通过
element.click()
触发它。有几种方法可以实现这一目标,但您绝对应该遵循“提升状态”的反应原则。 我会将

handleSaveQuestion

功能移至

addQuestionsPage
组件中,并将问题文本保留为问题对象中的状态。将其传递给
Question
组件,以及用于更改问题文本的回调。
    

© www.soinside.com 2019 - 2024. All rights reserved.