如何在ReactJS中使用refs来更改样式类

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

本文关键字:样式 refs ReactJS      更新时间:2023-09-26

当颜色值改变时,我试图改变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语法,所以请帮助解决这个问题。谢谢。

我找到了。下面是答案:

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

如果有人在寻找hooks版本

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

也可以用ref元素改变div的颜色。例如:

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