此科德芬使用conic-gradient创建边框。当您将鼠标移动到元素上时,您会看到渐变。JavaScript正在更新存储旋转角度的CSS自定义属性。边框图像源属性设置用于创建元素边框的源图像。与接受图像值的其他属性一样,任何CSS渐变类型也是有效的。
现在,当我试图用React中的样式组件重新创建它时,我得到了渐变边框。但是当我移动鼠标的时候,它并没有改变,就像在Codepen一样?
My App.tsx
import React from "react";
import styled from "styled-components";
export interface Props {
card: Element;
}
const Card = styled.div`
--startDeg: 0deg;
inline-size: 50vmin;
block-size: 50vmin;
border: 5vmin solid hsl(100 100% 60%);
border-image-slice: 1;
border-image-source: conic-gradient(
from var(--startDeg, 0deg),
hsl(100 100% 60%),
hsl(200 100% 60%),
hsl(100 100% 60%)
);
display: grid;
place-content: center;
padding: 4ch;
box-sizing: border-box;
font-size: 10vmin;
`;
function App() {
const card: Element = document.querySelector(".card");
window.addEventListener(
"mousemove",
({ clientX, clientY }) => {
const { x, y, width, height } = card.getBoundingClientRect();
const dx = clientX - (x + 0.5 * width);
const dy = clientY - (y + 0.5 * height);
const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
card.style.setProperty("--startDeg", `${angle + 90}deg`);
},
false
);
return <Card>Conic Gradient Border</Card>;
}
export default App;发布于 2022-08-10 15:49:10
在这个代码框示例中,您可以看到工作版本。(JS版)
代码:
import React, { useEffect, useRef, useCallback } from "react";
import styled from "styled-components";
const Card = styled.div`
--startDeg: 0deg;
inline-size: 50vmin;
block-size: 50vmin;
border: 5vmin solid hsl(100 100% 60%);
border-image-slice: 1;
border-image-source: conic-gradient(
from var(--startDeg, 0deg),
hsl(100 100% 60%),
hsl(200 100% 60%),
hsl(100 100% 60%)
);
display: grid;
place-content: center;
padding: 4ch;
box-sizing: border-box;
font-size: 10vmin;
`;
function App() {
const cardRef = useRef();
const mouseMoveListener = useCallback(({ clientX, clientY }) => {
const card = cardRef.current;
const { x, y, width, height } = card.getBoundingClientRect();
const dx = clientX - (x + 0.5 * width);
const dy = clientY - (y + 0.5 * height);
const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
card.style.setProperty("--startDeg", `${angle + 90}deg`);
}, []);
useEffect(() => {
window.addEventListener("mousemove", mouseMoveListener, false);
return () => window.removeEventListener("mousemove", mouseMoveListener);
}, [mouseMoveListener]);
return <Card ref={cardRef}>Conic Gradient Border</Card>;
}
export default App;解释:
基于React生命周期,querySelector不能正常工作,因为React组件在挂载组件时没有完成DOM的绘制。因此,使用ref将确保html元素将被正确定位。
此外,在初始挂载上注册useEffect中的侦听器并使用清理函数删除它以避免内存泄漏也是一种很好的做法。
https://stackoverflow.com/questions/73280296
复制相似问题