[英]How to use inline styles to use transform: rotate() with react.js on scroll
Creating this page.创建此页面。 I have an element I want to rotate on scroll.
我有一个要在滚动时旋转的元素。 Would prefer to use react syntax to create this 'animation'.
更愿意使用反应语法来创建这个“动画”。
LeftGear = () => {
const rotate = window.scrollY / 10 % Math.PI
const divStyle = {
backgroundColor: 'purple',
transform: `scroll(${rotate})`,
}
return <img
className={this.changeClassName('circleImage')}
src="../../assets/icons/red-gear.svg"
alt="Circles Icon"
style={divStyle}
/>
}
render(){
return <LeftGear/>
}
this works to give the image a background but does not work for that scroll.这可以为图像提供背景,但不适用于该滚动。 So Im wondering what I'm doing wrong ?
所以我想知道我做错了什么?
Rotations work with transform: rotate({n}deg)
where {n}
is your radius number.旋转与
transform: rotate({n}deg)
其中{n}
是您的半径数。 For the rest, bind and event listener to the window in an useEffect hook.其余的,在 useEffect 钩子中将事件侦听器绑定到窗口。 Instead of updating the
divStyle
object, just create a reference to the image and update the style.transform
property.无需更新
divStyle
对象,只需创建对图像的引用并更新style.transform
属性即可。
React has no smart way of dealing with this, so sometimes you just have to use some vanilla JS. React 没有聪明的方法来处理这个问题,所以有时你只需要使用一些普通的 JS。
import React, { useEffect, useRef } from 'react';
const LeftGear = () => {
const imageRef = useRef();
const divStyle = {
backgroundColor: 'purple',
}
useEffect(() => {
window.addEventListener('scroll', event => {
requestAnimationFrame(() => {
const rotation = window.scrollY / 10 % Math.PI;
imageRef.current.style.transform = `rotate(${rotation}deg)`;
});
});
}, []);
return (
<img
ref={imageRef}
className={this.changeClassName('circleImage')}
src="../../assets/icons/red-gear.svg"
alt="Circles Icon"
style={divStyle}
/>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.