如何配置react-rnd组件左侧resize行为以固定右边界
React-rnd 实现左侧缩放固定右边界
问题分析
默认使用react-rnd左侧缩放时,组件会固定左边界仅修改宽度,导致右边界随宽度变化移动,无法实现隐藏元素左侧内容的需求。要达到左侧缩放时右边界固定的效果,需要通过受控模式手动控制组件的位置(x坐标)和宽度,保持右边界(x + width)的位置不变。
解决方案步骤
- 使用React状态管理组件的位置和尺寸,替代默认的
default属性 - 监听缩放停止事件,判断缩放方向为左侧时,重新计算x坐标和宽度,确保右边界位置不变
- 保留容器的
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
相关产品推荐
相关产品推荐

