简体   繁体   English

React:如何打开新添加的手风琴项目?

[英]React: How to open a newly added accordion item?

I got an accordion component in my React application.我的 React 应用程序中有一个手风琴组件。 The user is able to add items to this accordion.用户可以向该手风琴添加项目。 Now, when the users clicks a button to add an item to the accordion, I would like for the newly added accordion item to automatically open.现在,当用户单击按钮将项目添加到手风琴时,我希望新添加的手风琴项目自动打开。 Here is a codesandbox displaying my problem .这是一个显示我的问题代码和框

To open and close the accordion, I use a bit of state: const [clicked, setClicked] = useState("0");要打开和关闭手风琴,我使用了一些状态: const [clicked, setClicked] = useState("0"); . .

When an accordionItem is clicked, the following function gets called:当单击一个accordionItem ,将调用以下函数:

  const handleToggle = (index) => {
    if (clicked === index) {
      return setClicked("0");
    }
    setClicked(index);
  };

In my codesandbox demo, I use an array of question and answers as accordionItems and I loop through them.在我的 codeandbox 演示中,我使用一系列问题和答案作为accordionItems并循环浏览它们。 So I thought that all I had to do was just use the setClicked function to set the clicked state equal to the length of the faqs array minus 1 in order to open the right accordion, but that is not working like expected...所以我认为我所要做的就是使用setClicked函数将clicked状态设置为等于 faqs 数组的长度减 1 以打开正确的手风琴,但这并不像预期的那样工作......

You have few problems.你的问题很少。

One is you must use newFaq below (because state variable doesn't get updated immediately):一种是您必须在下面使用newFaq (因为状态变量不会立即更新):

setClicked(newFaq.length - 1);

Second error you were getting when trying to access ref in render in style - since component was not committed to DOM yet, the ref was null.尝试在样式中访问ref时遇到的第二个错误 - 由于组件尚未提交给 DOM,因此ref为空。 You will need something like this:你将需要这样的东西:

 React.useEffect(() => {
    setHeight(contentEl.current.scrollHeight);
 });

and use height in style并在风格中使用height

style={active ? { height } : { height: "0px" }}

Also I think this is redundant:另外我认为这是多余的:

if (clicked === index) {
  return setClicked("0");
}

condition is never true.条件永远不是真的。

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

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