使用react-rnd的onResize属性时能否根据调整方向修改对应数值
react-rnd 高度调整专属逻辑实现方案
核心实现逻辑
你可以直接通过react-rnd自带的onResize回调的原生参数实现两个需求,10.3.4版本完全兼容以下写法:
- 仅Y轴调整触发状态更新:
onResize回调的第二个入参为direction,代表当前拖拽的锚点方向,仅当方向包含top/bottom(Y轴相关调整)时才执行状态更新逻辑,X轴方向(left/right)直接跳过即可。如果不需要X轴调整能力,也可以直接通过enableResizing配置关闭左右方向的拖拽锚点,避免用户误操作。 - 自动根据拖拽方向修改高度:
onResize回调的第四个入参为delta,其中delta.height就是本次拖拽的高度变化量:- 向下(bottom方向)拖拽时,高度增加,
delta.height为正数 - 向上(top方向)拖拽时,高度减少,
delta.height为负数
直接基于原始高度累加该值即可,不需要额外做方向判断。
- 向下(bottom方向)拖拽时,高度增加,
示例代码
import { useState } from 'react'; import { Rnd } from 'react-rnd'; const Resize = () => { const [itemHeight, setItemHeight] = useState(150); const handleResize = (_, direction, __, delta) => { // 过滤非Y轴方向的拖拽操作 const yAxisDirections = ['top', 'bottom', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight']; if (!yAxisDirections.includes(direction)) return; // 直接通过delta.height更新高度,自动适配上下拖拽方向 setItemHeight(prevHeight => prevHeight + delta.height); }; return ( <Rnd size={{ width: 300, height: itemHeight }} onResize={handleResize} // 可选配置:完全关闭X轴调整能力,仅保留上下拖拽锚点 enableResizing={{ top: true, bottom: true, left: false, right: false, topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }} > 仅可调整高度的组件 </Rnd> ); }; export default Resize;
内容的提问来源于stack exchange,提问作者Sujoy Dutta
相关产品推荐
相关产品推荐

