React-如何通过ref应用样式

时间:2020-04-13 13:07:03

标签: 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);

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

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

1 个答案:

答案 0 :(得分:3)

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>

相关问题