首页 > 解决方案 > 如何使用 React 函数组件向元素添加 CSS 类

问题描述

我想知道如何将 CSS 类添加到没有任何 CSS 类的元素。我正在寻找带有 Hooks 的 React 功能组件解决方案。在这里,我想将类添加到标记中,并且不需要提前添加 ${myclass} 。这意味着在我们执行 addclass 功能之前,标签应该没有任何属性。我尝试了以下方法,需要获得最佳实践。提前致谢!

function Trial(){
  const [myclass, changeclass] = useState("");
  const addclass=()=>{
  changeclass(`active`)
  }  
  return(
    <div>
      <h1 className={` ${myclass}`}>Hi</h1>
      <button onClick={addclass}>Click it</button>
    </div>
  )
}

标签: reactjsfunctionreact-hookscomponents

解决方案


您可以为此使用useRef()钩子:

function Trial(){
  const ref = useRef(null);
  const addclass=()=>{
     const h1 = ref.current; // corresponding DOM node
     h1.className = "active";
  }  
  return(
    <div>
      <h1 ref={ref} className="">Hi</h1>
      <button onClick={addclass}>Click it</button>
    </div>
  )
}

推荐阅读