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 badges1 Answer
Reset to default 4elementRef.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
评论列表(0条)