javascript - React - 如何通过 ref 应用样式

标签 javascript css reactjs jsx ref

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

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

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

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

最佳答案

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>

关于javascript - React - 如何通过 ref 应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61188568/

相关文章:

javascript - 在ExtJS中根据网格的记录/模型获取行HTML元素

css - 管理模块 css 在 prestashop 1.6 中不起作用

css - 如何居中 ngx-bootstrap 模态

reactjs - 更新后出错: Cannot resolve module 'react/lib/ReactMount'

reactjs - React 从子级获取父级 props 的正确方法是什么

javascript - 使用 React 或 jQuery 创建 DOMNode 以传递给谷歌地图 API

javascript - Windows Phone 8 图像比视口(viewport)宽

javascript - Angular Directive(指令)链接函数中的 "attrs"参数有什么用

javascript - 在 DOM 中存储数据的正确方法是什么

css - 使用 Flexbox 垂直居中文本并保持容器高度相同