Javascript 如何使用refs更改ReactJS中的样式类?
我试图在颜色值更改时更改Javascript 如何使用refs更改ReactJS中的样式类?,javascript,css,reactjs,css-modules,refs,Javascript,Css,Reactjs,Css Modules,Refs,我试图在颜色值更改时更改div的背景。下面是我接收颜色值的函数: ChangeColor(oColor) { this.props.ChangeColor(oColor); console.log("Refs: ", this.refs.colorPicker.className); }, 这是css类 .colorPicker { padding-right: 25px; background: #000; display: inline;
div
的背景。下面是我接收颜色值的函数:
ChangeColor(oColor) {
this.props.ChangeColor(oColor);
console.log("Refs: ", this.refs.colorPicker.className);
},
这是css类
.colorPicker {
padding-right: 25px;
background: #000;
display: inline;
margin-right: 5px;
}
这是我的div元素,它的背景需要在运行时更新
<div ref='colorPicker' className={this.GetClass("colorPicker")} />
我不确定refs synatx,因此请帮助解决此问题。谢谢。我找到了。以下是答案:
ChangeColor(oColor) {
this.props.ChangeColor(oColor);
this.refs.colorPicker.style.background = oColor; //this is how background will be updated
},
此外,还可以使用ref元素更改div的颜色。例如:
const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply
如果有人在找hooks版本
export const YourComponent=(道具)=>{
const divRef:=useRef(null);
yourTriggerEvent=()=>{
divRef.current.style.background='red';
}
返回(
);
}
有人能详细说明这个答案吗?还有一件事:改变样式对象的一个属性非常慢。如果要更改的样式是转换(即translate
,top
等),则应将此is请求包装在调用中