我正在尝试使用 React.js 中的功能组件来操作 DOM。当我将鼠标悬停在浮动方块上时,我希望浮动方块旋转一定度数,并尝试在我的 handleCursor 函数中操纵 DOM 中的元素。该样式表示它正在右侧的 console.logs 上进行更新,所以我不确定为什么实际的正方形本身不进行旋转。
我想要的内容显示在此 codepen 链接中:https ://codepen.io/rauldronca/pen/MZjEBd
这是一些JS代码
import React, {useEffect, useRef} from 'react';
import '../css/home.css';
const Home = () => {
// const bubbleRef = useRef(null);
// useEffect(() => {
// if(bubbleRef.current) {
// bubbleRef.current.style.transform = 'translateX(200px)';
// }
// console.log(bubbleRef.current);
// }, [bubbleRef])
const handleCursor = (e) => {
const bubbles = document.querySelectorAll('.bub');
const mouseX = e.pageX;
const mouseY = e.pageY;
bubbles.forEach(bubble => {
const bubbleX = bubble.offsetLeft + 20;
const bubbleY = bubble.offsetTop + 20;
const diffX = mouseX - bubbleX;
const diffY = mouseY - bubbleY;
const radians = Math.atan2(diffY, diffX);
const angle = radians * 180 / Math.PI;
bubble.style.transform = `rotate(${angle}deg)`;
console.log(bubble);
})
}
return (
<div className='bubbleContainer'>
<div className='bub1 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub2 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub3 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub4 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub5 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub6 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub7 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub8 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub9 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub10 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub11 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub12 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub13 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub14 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub15 bub' onMouseMove={e => handleCursor(e)}></div>
<div className='bub16 bub' onMouseMove={e => handleCursor}></div>
</div>
)
}
export default Home;
此外,我也尝试使用 useRef 挂钩,但它与我的 handleCursor 函数做同样的事情。方块仍然不会旋转(我注释掉了我的 useRefs 代码)