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

时间:2016-09-20 15:14:52

标签: 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;
    margin-right: 5px;
  }

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

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

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

3 个答案:

答案 0 :(得分:16)

我找到了。这是答案:

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

  },

答案 1 :(得分:3)

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

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

答案 2 :(得分:3)

如果有人正在寻找 hooks 版本

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

相关问题