简体   繁体   English

如何在功能组件中正确存储 refs

[英]How to store refs in functional component properly

I'm trying to create a component that tests english vocabulary.我正在尝试创建一个测试英语词汇的组件。
Basically, there are 4 options with 1 correct.基本上,有 4 个选项,其中 1 个正确。
When user chooses option, the right option is highlited in green, and the wrong one in red.当用户选择选项时,正确的选项以绿色突出显示,错误的选项以红色突出显示。
Then user can push the "next" button to go to the next batch of words.然后用户可以按下“下一步”按钮到 go 到下一批单词。

I store refs in object (domRefs, line 68).我将参考存储在 object(domRefs,第 68 行)中。
Populate it at line 80.在第 80 行填充它。
And remove all refs at line 115.并删除第 115 行的所有参考。
But it doesnt get removed, and leads to error (line 109)但它没有被删除,并导致错误(第 109 行)

https://stackblitz.com/edit/react-yocysc https://stackblitz.com/edit/react-yocysc

So the question is - How to store these refs and what would be the better way to write this component?所以问题是 - 如何存储这些引用以及编写这个组件的更好方法是什么?
Please help, Thanks.请帮忙,谢谢。

You shouldn't keep refs for component in global variable, since it's making your component singleton.您不应该将组件的引用保留在全局变量中,因为它会使您的组件成为 singleton。 To apply some styles just use conditional rendering instead.要应用一些 styles,只需使用条件渲染。 Also, it's better to split your test app into several separate components with smaller responsibilities:此外,最好将您的测试应用程序拆分为几个职责较小的独立组件:

const getClassName(index, selected, rightAnswer) {
  if (selected === null) {
    return;
  }

  if (index === rightAnswer) {
    return classes.rightAnswer;
  }

  if (index === selected) {
    return classes.wrongAnswer;
  }
}
const Step = ({ question, answers, rightAnswer, selected, onSelect, onNext }) => (
  <div ...>
    <div>{ question }</div>
    { answers.map(
      (answer, index) => (
        <Paper
          key={ index }
          onClick={ () => onSelect(index) }
          className={ getClassName(index, selected, rightAnswer) } 
    ) }
    { selected && <button onClick={ onNext() }>Next</button> }
  </div>
);

const Test = () => {
  const [ index, setIndex ] = useState();
  const word = ..., answers = ..., onSelect = ..., onNext = ...,

  return (
    <Question
      question={ word }
      answers={ answers }
      ... />
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM