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

React中如何实现switcher-btn与Ant Design Drawer联动移动?

实现开关按钮随Ant Design Drawer同步移动

要让switcher-btn随Drawer打开一起移动,核心是将按钮与Drawer置于同一个可滑动的容器内,通过状态控制容器的位置变化,替代AntD Drawer自带的独立滑入逻辑。具体修改如下:

修改React组件代码

给switcher-wrapper根据open状态添加open类,同时调整Drawer的属性,让它贴合容器而非使用自身固定定位:

const BasicLayout: React.FC = () => {
    const [open, setOpen] = useState(false);

    const toggleDrawer = () => {
        setOpen(!open);
    };

    return (
        <div className="wrapper">
            <div className={`switcher-wrapper ${open ? 'open' : ''}`}>
                <div className="switcher-btn" onClick={toggleDrawer}>
                    <i className='ri-settings-2-fill bg-cog bx-spin'></i>
                </div>
                <div className="switcher-body">
                    <Drawer 
                        title="Basic Drawer" 
                        placement="right" 
                        onClose={toggleDrawer} 
                        open={open}
                        mask={false}
                        style={{ position: 'static', width: '100%' }}
                        closable={false}
                    >
                        <p>Drawer</p>
                    </Drawer>
                </div>
            </div>
        </div>
    )
}

export default BasicLayout;

修改SCSS代码

添加open类的滑动样式,确保容器和按钮同步过渡:

.switcher-wrapper {
    width: 378px;
    height: 100%;
    position: fixed;
    right: -378px;
    top: 0;
    bottom: 0;
    transition: all .2s ease-out;
    background: #fff;
}

.switcher-wrapper.open {
    right: 0;
}

.switcher-btn {
    width: 40px;
    height: 40px;
    line-height: 40px;
    font-size: 24px;
    background: #008cff;
    box-shadow: 0 .3rem .6rem rgba(0, 0, 0, .13);
    color: #fff;
    text-align: center;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    position: absolute;
    top: 40%;
    right: 100%;
    cursor: pointer;
    transition: all .2s ease-out;
}

// 可选:打开时旋转图标提示关闭状态
.switcher-wrapper.open .switcher-btn i {
    transform: rotate(180deg);
    transition: transform .2s ease-out;
}

核心逻辑说明

  1. 将按钮和Drawer统一放在switcher-wrapper固定容器中,默认容器隐藏在屏幕右侧外。
  2. 当open状态为true时,容器的right属性变为0,整个容器(包括按钮和Drawer)同步滑入屏幕。
  3. 调整Drawer为position: static,让它跟随容器移动而非使用自身独立定位,同时设置宽度为100%填满容器。
  4. 按钮点击事件改为切换open状态,保持交互逻辑统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:54:52