React中如何在事件完成后动态关闭MUI临时Drawer
跨组件关闭MUI Drawer的解决方案
因为Drawer的状态由ButtomNavigation组件管理,而触发关闭的逻辑在子组件ItemModule里,我们可以通过父组件传递回调函数的方式实现,这是React父子组件通信最直接的方案,不需要额外依赖。
步骤1:在ButtomNavigation中定义关闭函数并传递给子组件
修改ButtomNavigation.js,添加专门的关闭Drawer函数,然后通过props传给ItemModule:
const ButtomNavigation = (props) => { const [state, setState] = React.useState({ top: false, left: false, bottom: false, right: false, }); const toggleDrawer = (anchor, open) => (event) => { if ( event && event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift') ) { return; } setState({ ...state, [anchor]: open }); }; // 新增:专门关闭bottom Drawer的函数 const closeBottomDrawer = () => { setState(prevState => ({ ...prevState, bottom: false })); }; return ( <> <div className='d-flex justify-content-between item-bottom-nav'> <div className='d-flex justify-content-end cart-and-buy-now'> <button id="addCart" onClick={toggleDrawer('bottom', true)}>Add to cart</button> <button id="buyNow" onClick={toggleDrawer('bottom', true)}>Buy now</button> </div> </div> <div > {['bottom'].map((anchor) => ( <React.Fragment key={anchor}> <SwipeableDrawer anchor={anchor} open={state[anchor]} onClose={toggleDrawer(anchor, false)} onOpen={toggleDrawer(anchor, true)} PaperProps={{ sx:{height: 'calc(100% - 60px)', top: 60,borderTopLeftRadius:'10px',borderTopRightRadius:'10px'} }} > {props.Data !=null && <> {/* 新增:传递关闭回调给ItemModule */} <ItemModule Data={props.Data} onCloseDrawer={closeBottomDrawer} /> </> } </SwipeableDrawer> </React.Fragment> ))} </div> </> ); }; export default ButtomNavigation;
步骤2:在ItemModule中调用关闭函数
修改ItemModule.js,从props中拿到onCloseDrawer,在请求成功后调用它:
const ItemModule = (props) => { const addToCart = async (cartItem) => { try { const response = await axiosPrivate.post("/cart", JSON.stringify({ cartItem }), { signal: controller.signal }); console.log(response?.data); // 请求成功后关闭Drawer props.onCloseDrawer(); } catch(err) { // 错误处理逻辑 } }; // 组件其他逻辑... }; export default ItemModule;
补充说明
如果你的项目已经使用了Redux、Zustand等状态管理库,也可以把Drawer的状态放到全局状态中,在ItemModule里直接修改全局状态来关闭Drawer,但对于这种简单的父子组件场景,props传递回调是最轻量化的方案,不需要额外引入状态管理的复杂度。
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

