gpt4 book ai didi

reactjs - 如何使用 React 功能组件将 CSS 类添加到元素

转载 作者:行者123 更新时间:2023-12-05 01:28:43 24 4
gpt4 key购买 nike

我想知道如何将 CSS 类添加到没有任何 CSS 类的元素。我正在寻找带有 Hooks 的 React Functional 组件解决方案。在这里,我想将类添加到标签中,我不需要提前添加 ${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>
)
}

最佳答案

可以添加一个id,然后通过queryselector操作DOM中的元素

在要更改其类名的元素中

 <h1 className={`${myclass}`} id = "change-class">Hi</h1>

然后在函数中

  const addclass=()=>{
document.querySelector("#change-class").classList.add('new-class-name');
}

所以整个代码看起来像这样

function Trial(){
const addclass=()=>{
document.querySelector("#change-class").classList.add('new-class-name');
}

return(
<div>
<h1 className={`${myclass}`} id = "change-class" >Hi</h1>
<button onClick={addclass}>Click it</button>
</div>
)
}

更多信息请查看herehere

关于reactjs - 如何使用 React 功能组件将 CSS 类添加到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68358361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com