我有一个组件,我想动态编辑一些样式。当我进入组件时,我希望它平稳增长,当我离开时,我希望它平稳缩短。
这是我的代码:
const easing = 0.1;
const outScale = 0.6;
const inScale = 1;
let targetScale = outScale;
let elementScale = targetScale;
let innerScale = 1 / elementScale;
const [parentTransformStyle, setParentTransformStyle] = useState(
`scale(${elementScale})`
);
const [innerTransformStyle, setInnerTransformStyle] = useState(
`scale(${innerScale})`
);
const requestRef = useRef();
const onPointOverEvent = () => {
targetScale = inScale;
console.log("over", inScale, targetScale);
};
const onPointerOutEvent = () => {
targetScale = outScale;
console.log("out", outScale, targetScale);
};
const animate = () => {
console.log("animate", targetScale);
elementScale += (targetScale - elementScale) * easing;
innerScale = 1 / elementScale;
setParentTransformStyle(`scale(${elementScale})`);
setInnerTransformStyle(`scale(${innerScale})`);
requestAnimationFrame(animate);
};
useEffect(() => {
requestRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(requestRef.current);
}, []);
当鼠标悬停在元素中和鼠标离开元素时,应该更新变量targetScale
。
如果我在事件侦听器中打印值,则该值是正确的。但是,在animate
函数中,它具有初始值。有人可以指出我错过了什么吗?
有什么理由不能使用CSS转换而不是自己制作动画吗?
例:
function MyComponent() {
const [innerTransformStyle, setInnerTransformStyle] = React.useState(
`scale(${0.6})`
);
const onPointOverEvent = () => {
setInnerTransformStyle(`scale(${1})`);
};
const onPointerOutEvent = () => {
setInnerTransformStyle(`scale(${0.6})`);
};
return (
<div className="parent">
<div className="element" style={{transform: innerTransformStyle}} onPointerOut={onPointerOutEvent} onPointerOver={onPointOverEvent}></div>
</div>
);
}
ReactDOM.render(<MyComponent/>, document.getElementById("app"));
.parent {
width: 100px;
height: 100px;
background-color: #f00;
}
.element {
width: 100px;
height: 100px;
background-color: #0f0;
transition: transform 1s;
}
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="app"></div>