reactjs - 如何使用 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>
)
}
解决方案
您可以为此使用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>
)
}
推荐阅读
- python - Python:每行数组的加权百分位数
- powershell - 在 Get-Mailbox cmdlet 的 GrantSendOnBehalfTo 属性中返回唯一用户 ID
- xml - XSLT:替换没有原始节点文本的元素/节点
- javascript - 你如何使用谷歌图表工具提示和 json 来提取元数据
- elasticsearch - es 关键字类型的最简单小写示例
- python - 如何将行的值转换为列
- c# - 在 Controller 操作返回后,如何强制立即释放 Scoped 服务?
- kubernetes - 配置 Istio、Kubernetes 和 MetalLB 以使用 Istio LoadBalancer
- c - 为什么会出现浮点异常 8?
- python - Python tkinter:使用一个按钮选择一个txt文件,另一个按钮打开并读取内容到字符串