2 回答

TA貢獻1804條經驗 獲得超7個贊
組件僅在狀態或道具更新時重新渲染。 沒有狀態或道具,所以它永遠不會重新渲染,因此孩子永遠不會重新渲染。AppCursor
您可以使用附加到的 ref,并直接設置頂部和左側屬性。請不要忘記在卸載組件時刪除事件偵聽器。Cursor
import React, { useEffect, useRef } from "react";
import "./styles.css";
import styled from "styled-components";
const Cursor = styled.div`
height: 30px;
width: 30px;
border-radius: 50%;
border: 1.5px solid black;
position: absolute;
`;
export default function App() {
const posRef = useRef(null);
const cursor = e => {
const { clientX = 0, clientY = 0 } = e;
posRef.current.style.left = clientX + "px";
posRef.current.style.top = clientY + "px";
// console.log(clientX, clientY);
};
useEffect(() => {
window.addEventListener("mousemove", cursor);
return () => window.removeEventListener("mousemove", cursor);
}, []);
return (
<div className="App">
<h1>Demo</h1>
<Cursor ref={posRef} />
</div>
);
}
編輯
正如@KirillSkomarovskiy所指出的那樣,使用狀態并不是使頁面陷入困境并崩潰的原因。我懷疑這是/正在添加多個/重復的處理程序,這些處理程序沒有被正確清理(可能通過記錄每個更新的位置來增加)。mousemove
const Cursor = styled.div`
height: 30px;
width: 30px;
border-radius: 50%;
border: 1.5px solid black;
position: absolute;
transform: translate(-50%, -50%);
top: ${props => props.yPos};
left: ${props => props.xPos};
`;
export default function App() {
const [pos, setPos] = useState({ x: 0, y: 0 });
useEffect(() => {
const cursor = e => {
setPos({
x: e.clientX + "px",
y: e.clientY + "px"
});
// console.log(e.clientX, e.clientY);
};
window.addEventListener("mousemove", cursor);
return () => window.removeEventListener("mousemove", cursor);
}, []);
return (
<div className="App">
<h1>Demo</h1>
<Cursor xPos={pos.x} yPos={pos.y} />
</div>
);
}

TA貢獻1911條經驗 獲得超7個贊
變量 永遠不會被有效地更新,因為它是一個 ES6 箭頭函數,它以某種方式工作,所以如果你想從 傳遞值到 或 ,那么你也應該把它們當作函數:xycursor()functionalcursor()xy
x = (callback) =>{
return callback;
}
y = (callback) =>{
return callback;
}
現在,您可以將值傳遞給 和 :xy
const cursor = (e) => {
x (e.screenX + 'px');
y (e.screenY + 'px');
}
然后,您的事件偵聽器調用 :cursor(e)
window.addEventListener('mousemove', cursor);
無論你想在哪里使用的值,你只需要稱它們為:或.xyx()y()
這就是工作原理!ES6 Functional Programming
添加回答
舉報