Javascript 我如何使用 refs 来更改 ReactJS 中的样式类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39597804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:43:26  来源:igfitidea点击:

How I can use refs to change styling class in ReactJS?

javascriptcssreactjscss-modulesrefs

提问by Muhammad Ateeq Azam

I'm trying to change background of a divwhen color value changes. Here is my function which receives color value:

div当颜色值改变时,我试图改变 a 的背景。这是我接收颜色值的函数:

ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    console.log("Refs: ", this.refs.colorPicker.className);
  },

Here is css class

这是css类

.colorPicker {
    padding-right: 25px;
    background: #000;
    display: inline;
    margin-right: 5px;
  }

and here is my div element whose background needs to update on run-time.

这是我的 div 元素,其背景需要在运行时更新。

<div ref='colorPicker' className={this.GetClass("colorPicker")}  />

I'm not sure about refs synatx so please help to fix this issue. Thanks.

我不确定 refs synatx,所以请帮助解决这个问题。谢谢。

回答by Muhammad Ateeq Azam

I found it. Here is answer:

我找到了。这是答案:

  ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    this.refs.colorPicker.style.background = oColor; //this is how background will be updated

  },

回答by osvaldo carrillo

Also, you can change the color of the div with the ref element. For example:

此外,您可以使用 ref 元素更改 div 的颜色。例如:

const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply