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; }
核心逻辑说明
- 将按钮和Drawer统一放在
switcher-wrapper固定容器中,默认容器隐藏在屏幕右侧外。 - 当
open状态为true时,容器的right属性变为0,整个容器(包括按钮和Drawer)同步滑入屏幕。 - 调整Drawer为
position: static,让它跟随容器移动而非使用自身独立定位,同时设置宽度为100%填满容器。 - 按钮点击事件改为切换
open状态,保持交互逻辑统一。
内容的提问来源于stack exchange,提问作者Malikov Gulomjon
相关产品推荐
相关产品推荐

