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

自定义antD Drawer时onClose失效、标题自定义相关问题咨询

问题1:onClose函数不生效问题

  • 原因:代码中设置了closable={false},部分版本的antD中该配置会阻断默认关闭逻辑对onClose回调的触发,仅保留ESC、遮罩点击的关闭交互但不触发自定义回调。未显式声明maskClosable时也可能出现点击遮罩不触发回调的情况。
  • 解决方法:
    1. 显式添加maskClosable={true}和keyboard={true}属性,保证交互触发逻辑正常
    2. 如果不需要显示默认关闭按钮,不要直接设closable={false},可以设为closable={true}后通过CSS隐藏默认关闭按钮,保证回调链路正常

问题2:自定义标题实现问题

  • 原因:extra属性本身是antD预留的标题栏右侧拓展区域,所有传入内容默认都会居右展示,不适合用来定义标题主体内容。
  • 解决方法:直接使用title属性支持传入ReactNode的特性,自定义标题结构,左侧加图标、主副标题的布局直接写在title属性值内即可。

调整后的完整代码

import { InfoCircleOutlined, CloseOutlined } from '@ant-design/icons'; // 也可以替换为自定义图片资源
import { Drawer, Space, Typography } from 'antd';
const { Title, Text } = Typography;

// 业务逻辑保留
const [visible, setVisible] = useState(false);
const showDrawer = () => {
  setVisible(true);
};

const onClose = () => {
  console.log('hi')
  setVisible(false);
};

<Drawer
  // 自定义标题结构:左侧图标+主副标题
  title={
    <Space align="center">
      <InfoCircleOutlined style={{ color: '#1677ff' }} /> {/* 替换为你需要的(i)图标 */}
      <div>
        <Title level={5} style={{ margin: 0 }}>Grouped</Title>
        <Text type="secondary" style={{ fontSize: '12px' }}>自定义副标题内容</Text>
      </div>
    </Space>
  }
  width={"35%"}
  placement="right"                      
  closable={true}
  onClose={onClose}
  visible={visible}
  maskClosable={true}
  keyboard={true}
  extra={
    <span onClick={onClose}>
      <img src={crossImg} alt="关闭" />
    </span>
  }
  // 如需要隐藏默认关闭按钮,放开以下样式配置即可
  // styles={{
  //   header: {
  //     '.ant-drawer-close': {
  //       display: 'none'
  //     }
  //   }
  // }}
  >
     <div className="multi-country-drawer">
       {multiCountryGroup()}
     </div>
</Drawer>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:36:05