Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用refs更改ReactJS中的样式类?_Javascript_Css_Reactjs_Css Modules_Refs - Fatal编程技术网

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请求包装在调用中