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

Muh*_*zam 11 javascript css refs reactjs css-modules

我正在尝试更改div颜色值更改时的背景.这是我的函数,它接收颜色值:

ChangeColor(oColor) {
    this.props.ChangeColor(oColor);
    console.log("Refs: ", this.refs.colorPicker.className);
  },
Run Code Online (Sandbox Code Playgroud)

这是css类

.colorPicker {
    padding-right: 25px;
    background: #000;
    display: inline;
    margin-right: 5px;
  }
Run Code Online (Sandbox Code Playgroud)

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

<div ref='colorPicker' className={this.GetClass("colorPicker")}  />
Run Code Online (Sandbox Code Playgroud)

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

Muh*_*zam 18

我找到了.这是答案:

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

  },
Run Code Online (Sandbox Code Playgroud)

  • 有人可以详细说明这个答案吗? (4认同)
  • 还有一件事:改变样式对象的属性之一非常慢。您应该将此请求包装在 [window.requestAnimationFrame()](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) 调用中 (2认同)

Jon*_*ero 10

如果有人正在寻找 hooks 版本

export const YourComponent = (props) => {
  const divRef: = useRef(null);
  
  yourTriggerEvent = () => {
    divRef.current.style.background = 'red';
  }
  
  return (
    <div ref={divRef}>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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

const myReference = this.colorPicker.current // The DOM element
myReference.style.backgroundColor = "red"; // The style you want to apply
Run Code Online (Sandbox Code Playgroud)