【问题标题】:React - How to apply styles via refReact - 如何通过 ref 应用样式
【发布时间】:2020-07-26 01:15:05
【问题描述】:

我有一个容器的参考,我想更改他的背景位置。 这需要在函数内部发生,并且值是动态的,所以我不能为此创建一个类。

slideRef.current.style["background-position-x"] = "-262.5px"
setTimeout(function(){
  slideRef.current.classList.add("spin_animation");
  slideRef.current.style = {backgroundPositionX: "-" + scrollAmount + "px"}
 10);

我尝试了两种方法,访问属性而不使用驼峰式大小写,另一种是将样式作为对象传递,如内联样式。

如何应用背景位置,直接访问参考?

【问题讨论】:

    标签: javascript css reactjs jsx ref


    【解决方案1】:
    elementRef.current.style.backgroundPositionX = "-262.5px";
    

    const App = () => {
      const elementRef = React.useRef(null);
      const handler = () => {
        if (elementRef.current) {
          elementRef.current.style.color = "red";
          elementRef.current.style.backgroundPositionX = "-262.5px";
          console.log(elementRef.current.style);
        }
      };
      return (
        <div className="App">
          <h1 ref={elementRef}>Sample Text</h1>
          <h2 onClick={handler}>Click me to change the style of the text</h2>
        </div>
      );
    }
    ReactDOM.render(<App />, document.getElementById("root"));
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多