[英]Update className using react hook
I have a span which has a className.我有一个具有类名的跨度。 The span has two state, one is like
跨度有两个state,一个就像
<span key={uuid()} ref = {colorRef} className = 'singleWord'>{word}</span>
and the other is like另一个就像
<span key={uuid()} ref = {colorRef} className = 'singleWord redword'>{word}</span>
Now what I want is to check the className value like className.classList.contain("oneClass') which we do in vanilla js but I need in react hook(may be with ref hook) and also add className and remove className. also is it possible to check the length of className.for example 'singleword redword' should give length 2. So overall I need -现在我想要的是检查 className 值,例如 className.classList.contain("oneClass') 我们在 vanilla js 中做的,但我需要在 react hook(可能带有 ref hook)中,还添加 className 并删除 className。也是可以检查 className 的长度。例如“singleword redword”的长度应该为 2。所以总的来说我需要 -
You can store in state an array of classes and use that to get all the information you need plus it gives an easy way to toggle any class in a set of classes.您可以在 state 中存储一个类数组,并使用它来获取您需要的所有信息,而且它提供了一种在一组类中切换任何 class 的简单方法。
basically this handleClasses
function takes a class argument and then checks whether that class is already in your state. If it is, it removes it, if it's not, it add it to the state. Then in your span you join all the classes in the array in state to make a single string of classes.基本上这个
handleClasses
function 需要一个 class 参数,然后检查 class 是否已经在你的 state 中。如果是,它会删除它,如果不是,它会将它添加到 state。然后在你的跨度中你加入所有类state 中的数组以生成单个类字符串。
Also you get the number of classes applied to your element very easily by doing classes.length
您还可以通过执行
classes.length
非常轻松地获得应用于元素的类数
import React, { useState } from 'react';
const Component = () => {
const [classes, setClasses] = useState(['singleWord']);
const numberOfClasses = classes.length;
const handleClasses = (c) => {
setClasses(classes.includes(c)
? classes.filter((cls) => cls !== c)
: [...classes, c]
)
}
return (
<span
onClick={() => handleClasses(passClassToToggleHere)}
className={classes.join(' ')}
>
text
</span>
)
};
If you are using colorRef = useRef()
hook, then you can obtain the target node by calling colorRef.current
and proceed with vanilla js methods like colorRef.current.classList.contain("oneClass')
and so on.如果您使用的是
colorRef = useRef()
挂钩,则可以通过调用colorRef.current
获取目标节点,然后继续使用colorRef.current.classList.contain("oneClass')
等普通 js 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.