我想用 react 來制作像時鐘一樣的東西。我希望在 ref 的幫助下做到這一點,但有時它不起作用。這項任務是否有另一種解決方案,或者我做錯了什么?
import React, { useRef } from 'react';
import classes from "./Synchroniser.module.css";
const Synchroniser = () => {
const point:any = useRef(null);
var k = 0;
if (point.current !== null) {
setInterval(()=>{
if(k<360){
k ;
console.log(k);
}else{k=0}
point.current.style.transform = `rotate(${k}deg)`;
},100);
}else{
console.log(0)
}
return(
<div>
<h1 ref={point}>RLY?</h1>
</div>
);
};
export default Synchroniser
uj5u.com熱心網友回復:
到底部查看純 CSS 解決方案
反應解決方案
這解決了你的問題,但是 k 變數增加了兩倍,我不知道為什么。為了使 k 變數在狀態之間保持不變,并且每次重新渲染都不會重置時鐘,您也必須將它與 useRef 一起使用。
const point = useRef(null);
const k = useRef(0);
useEffect(() => {
if (point.current !== null) {
setInterval(() => {
if (k.current < 360) {
k.current = k.current 1;
} else {
k.current = 0;
}
point.current.style.transform = `rotate(${k.current}deg)`;
}, 1000);
} else {
console.log("0");
}
},[]);
CSS 解決方案 CodeSandbox 鏈接
JSX
<div className="clock">
<div className="spin"></div>
</div>
CSS
.clock {
height: 250px;
width: 250px;
border-radius: 9999px;
display: flex;
justify-content: center;
align-items: center;
background: #eeeeee;
}
.spin {
width: 90%;
height: 2px;
position: relative;
background: white;
-webkit-animation:spin 60s linear infinite;
-moz-animation:spin 60s linear infinite;
animation:spin 60s linear infinite;
}
.spin::after,
.spin::before {
height: 2px;
content: " ";
position: absolute;
top: 0;
width: 50%;
}
.spin::after {
right: 0;
background-color: black;
}
.spin::before {
left: 0;
background-color: #eeeeee;
}
@-moz-keyframes spin {
100% {
-moz-transform: rotate(360deg);
}
}
@-webkit-keyframes spin {
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes spin {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/460476.html
標籤:javascript 反应
上一篇:如何更好地近似粗貝塞爾曲線?
