如何使用 refs 访问/覆盖元素的 className? [英] How to access/override the className of an element using refs?
本文介绍了如何使用 refs 访问/覆盖元素的 className?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本和一个按钮.
I have a text and a button.
我想要实现的是这样的,如果我单击按钮,文本将被隐藏.我想在不使用状态的情况下实现这一点.
What I want to achieve is something like this, that if I clicked the Button the Text will be hidden. I want to achieve this without using state.
class Test extends Component {
constructor(props){
//codes
}
hide = () => {
const span = this.refs.spanLoading;
span.ClassName = "hidden";
}
render() {
return (
<span ref="spanLoading" id="test-id" className="">The Quick Brown Fox.</span>
<button onClick={() => this.hide()}>Hide</button>
);
}
}
export default Test;
推荐答案
您可以使用 useRef()
钩子.
You can use useRef()
hook.
维护一个 ref
对象,它不是一个字符串.
Maintain one ref
object which is not a string.
function Test() {
const ref = useRef(null);
const onClick = () => {
const span = ref.current; // corresponding DOM node
span.className = "hidden";
};
return (
<>
<span ref={ref} id="test-id" className="">
The Quick Brown Fox.
</span>
<button onClick={onClick}>Hide</button>
</>
);
}
// css
.hidden {
display: none;
}
参见工作沙盒
这篇关于如何使用 refs 访问/覆盖元素的 className?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文