【问题标题】:How I can use refs to change styling class in ReactJS?如何使用 refs 更改 ReactJS 中的样式类?
【发布时间】:2017-01-28 14:20:08
【问题描述】:

我正在尝试在颜色值更改时更改 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,所以请帮助解决这个问题。谢谢。

【问题讨论】:

    标签: javascript css reactjs css-modules refs


    【解决方案1】:

    我找到了。这是答案:

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

    【讨论】:

    • 有人能详细说明这个答案吗?
    • 还有一件事:改变样式对象的属性之一非常慢。您应该将此请求包装在 window.requestAnimationFrame() 调用中
    • 特别是如果您要更改的样式是转换(即translate、top 等)
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果有人在寻找 hooks 版本

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

      【讨论】:

        猜你喜欢
        • 2014-04-13
        • 2014-09-11
        • 2022-12-16
        • 1970-01-01
        • 2019-10-26
        • 2020-09-29
        • 1970-01-01
        • 2019-05-09
        • 2019-07-27
        相关资源
        最近更新 更多