类型错误:无法读取空 React 选项卡的属性“classList”

时间:2021-07-21 08:02:07

标签: reactjs tabs use-ref

我尝试使用 useRef 在 React 中创建选项卡。每个选项卡将显示不同的内容。一切都好 。 我的选项卡可以工作,但是当您单击 3 次或更多次时会引发此错误 - 无法读取 null 的属性类列表。我不知道原因,因为它工作正常,但是经过三次或更多次尝试后失败并抛出错误。 我的代码如下所示:





function Panel({className,children,Ref}){
    return <div ref={Ref} className={`scth-panel ${className}`}>{children}</div>
}

function SingleCourseTab({head,children}) {
    
    const tabRefs = useRef([]);
    const tabHeadRefs = useRef([]);

    function tabClickHandle(e,index){
       tabRefs.current.forEach((item,refIndex) => {
          if(index === refIndex){
              console.log(item)
              item.classList.add('panel-active');
              tabHeadRefs.current[refIndex].classList.add('head-active');
          }else{
            item.classList.remove('panel-active');
            tabHeadRefs.current[refIndex].classList.remove('head-active');
          }
       })
    }

    return (
    <div className='single-course-tab'>
         <div className='single-course-tab-head'>
             <ul>
                 {
                     head.map((item, index)=>(
                        <li 
                          key={index}
                          ref={ref => tabHeadRefs.current.push(ref)}
                          onClick={(e) => tabClickHandle(e,index)} 
                          className={`scth-${index} ${index===0?'head-active':''}`} 
                          >
                              {item}
                          </li>
                     ))
                 }
             </ul>
         </div>
         <div className='single-course-tab-body'>
            {
                children.map((item,index) => (
                  <Panel
                     
                     key={index}
                    Ref={ref => tabRefs.current.push(ref)}
                   className={`scth-panel-${index} ${index===0?'panel-active':''}`}>
                    {
                        item
                    }
                  </Panel>    
                ))
            }
         </div>
    </div>
      )
}

SingleCourseTab.Panel = Panel;

export default SingleCourseTab

0 个答案:

没有答案