React-rnd子组件调整大小时如何按比例调整font-size?

问题描述 投票:0回答:1

我正在尝试制作一个可拖动的组件来模拟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
值较高时,字体大小会呈指数增长或缩小。

代码沙箱:https://codesandbox.io/s/elegant-khorana-3wwb3r

reactjs draggable
1个回答
0
投票

这个问题你有解决办法吗?

© www.soinside.com 2019 - 2024. All rights reserved.