javascript - React - How to apply styles via ref - Stack Overflow

I have a reference for a container and I want to change his background-position. That needs to happen

I have a reference for a container and I want to change his background-position. That needs to happen inside of a function and the values are dynamic, so I can't create a class for that.

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

I tried two ways, accessing a property and not using a camel case and the other one was passing the style as an object like an inline style.

How can I apply the background-position, accessing directly the ref?

I have a reference for a container and I want to change his background-position. That needs to happen inside of a function and the values are dynamic, so I can't create a class for that.

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

I tried two ways, accessing a property and not using a camel case and the other one was passing the style as an object like an inline style.

How can I apply the background-position, accessing directly the ref?

Share Improve this question edited Apr 13, 2020 at 14:23 keikai 15.2k10 gold badges55 silver badges72 bronze badges asked Apr 13, 2020 at 13:07 Laura BeatrisLaura Beatris 1,9329 gold badges31 silver badges57 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4
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./ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745419994a4626921.html

相关推荐

  • javascript - React - How to apply styles via ref - Stack Overflow

    I have a reference for a container and I want to change his background-position. That needs to happen

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信