我正在尝试制作一个可拖动的组件来模拟meme生成器的组件,但是当拖动的容器改变其大小时,未能使文本的字体大小按比例增大和缩小。 这是我尝试过的:
const App = () => {
const [fontSize, setFontSize] = useState(16);
const textRef = useRef(null);
const handleResize = (e, direction, ref, delta, position) => {
// Update the font size based on the resize delta and the maximum font size
const deltaRatio = Math.sqrt(delta.width * delta.width + delta.height * delta.height);
if(delta.width + delta.height > 0) {
const newFontSize = Math.floor(fontSize + deltaRatio / 5);
setFontSize(newFontSize);
} else {
const newFontSize = Math.floor(fontSize - deltaRatio / 5);
setFontSize(newFontSize);
}
};
return (
<Rnd
// size={{ width: "300px", height: "200px" }}
onResizeStop={handleResize}
minWidth={100}
minHeight={100}
enableResizing={{
top: false,
right: true,
bottom: true,
left: false,
topRight: false,
bottomRight: true,
bottomLeft: false,
topLeft: false,
}}
style={{ border: '1px dashed' }}
>
<p ref={textRef} style={{ fontSize: `${fontSize}px` }}>
This is some sample text that will change in font size.
</p>
</Rnd>
);
};
handleResize()
内部逻辑的问题是,只有当delta
值较小时,它才会按预期缩放,但当delta
值较高时,字体大小会呈指数增长或缩小。
这个问题你有解决办法吗?