You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置react-rnd组件左侧resize行为以固定右边界

React-rnd 实现左侧缩放固定右边界

问题分析

默认使用react-rnd左侧缩放时,组件会固定左边界仅修改宽度,导致右边界随宽度变化移动,无法实现隐藏元素左侧内容的需求。要达到左侧缩放时右边界固定的效果,需要通过受控模式手动控制组件的位置(x坐标)和宽度,保持右边界(x + width)的位置不变。

解决方案步骤

  1. 使用React状态管理组件的位置和尺寸,替代默认的default属性
  2. 监听缩放停止事件,判断缩放方向为左侧时,重新计算x坐标和宽度,确保右边界位置不变
  3. 保留容器的overflow: hidden样式,实现超出部分隐藏

完整代码示例

import { useState } from 'react';
import Rnd from 'react-rnd';

const VisaScaler = ({ visa }) => {
  const [componentState, setComponentState] = useState({
    x: 0,
    y: 0,
    width: 250,
    height: 60,
  });

  const style = {
    display: 'flex',
    position: 'relative',
    border: 'solid 1px #ddd',
    overflow: 'hidden',
  };

  const resizeDirections = {
    bottom: false,
    bottomLeft: false,
    bottomRight: false,
    left: true,
    right: true,
    top: false,
    topLeft: false,
    topRight: false,
  };

  const handleResizeStop = (e, direction, ref, delta, position, size) => {
    if (direction === 'left') {
      // 计算原始右边界位置,确保缩放后保持不变
      const originalRight = componentState.x + componentState.width;
      // 新宽度为缩放后的宽度,新x坐标 = 原始右边界 - 新宽度
      const newX = originalRight - size.width;
      setComponentState({
        ...componentState,
        x: newX,
        width: size.width,
      });
    } else if (direction === 'right') {
      // 右侧缩放保持默认逻辑,固定左边界,仅修改宽度
      setComponentState({
        ...componentState,
        width: size.width,
      });
    }
  };

  return (
    <Rnd
      style={style}
      enableResizing={resizeDirections}
      // 使用受控属性绑定状态
      position={{ x: componentState.x, y: componentState.y }}
      size={{ width: componentState.width, height: componentState.height }}
      onResizeStop={handleResizeStop}
    >
      <img id="visaImage" src={visa} alt="VISA" />
    </Rnd>
  );
};

export default VisaScaler;

关键逻辑说明

  • 当触发左侧缩放(direction === 'left')时,通过原始右边界 = 初始x + 初始宽度计算固定位置,再用新x坐标 = 原始右边界 - 缩放后宽度得到新的位置,确保右边界始终不变
  • 右侧缩放保持默认行为,固定左边界仅调整宽度,符合原有预期
  • 容器的overflow: hidden样式确保超出容器范围的图片部分被隐藏,实现左侧缩放时隐藏'V'、右侧缩放时隐藏'A'的效果

内容的提问来源于stack exchange,提问作者ilketorun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:36:20