gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:10:25 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com