如何使用useRef在React Hooks中获得被点击的元素

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

我正在与React Hooks一起玩,我试图制造一个手风琴。我正在尝试从数组迭代它。所以我有2data,当我管理索引时,我得到的是被单击按钮的确切索引。但是,当我操纵ref时,我得到的是第二个的ref而不是第一个的ref。

这是怎么回事?反应中是否有错误?

这里是示例代码

 const content = useRef(null);


    const accordionClick = (id) => {
        setHeightState(setActive === false ? "0px" : `${content.current.scrollHeight}px`);
        SetCustomIndex(id);
        console.log(id);
        console.log(content );
    };

 items.general.map((data, index) => (
      <div className={`accordion-container`} key={index}>
         <button className{`accordion ${setActive}`} onClick{()=>accordionClick(index)}>
            {data}
          </button>

           <div
              className={`panel`}
              ref={content}
              data-id={index}
              style={{
                height: `${setHeight}`,
             }}
               data-id={index}
            >
             <p className="description-14">{data.item.main}</p>
            </div>
reactjs
1个回答
0
投票

因为您正在使用map(),所以将ref与Array一起使用

const inputRef = useRef([]);

ref={el => inputRef.current[index] = el}
inputRef.current[index];
© www.soinside.com 2019 - 2024. All rights reserved.