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

如何在ReactJS中实现点击按钮时显示自定义确认对话框?

在React中实现带自定义确认消息的按钮操作

方案一:使用原生浏览器确认框(快速实现)

这种方式无需额外依赖,直接用浏览器自带的confirm()函数就能搞定,适合对UI样式要求不高的快速开发场景。

核心逻辑:给每个按钮绑定点击事件,触发时先弹出对应消息的确认框,用户点击「确定」后再执行对应的业务操作。

示例代码:

import { useState } from 'react';

function ActionButtons() {
  // 模拟删除用户的业务操作
  const handleDeleteUser = () => {
    console.log('用户已删除');
    // 实际场景中可替换为API请求、状态更新等逻辑
  };

  // 模拟删除服务器的业务操作
  const handleDeleteServer = () => {
    console.log('服务器已删除');
  };

  return (
    <div>
      <button
        onClick={() => {
          if (confirm('确定要删除用户吗?')) {
            handleDeleteUser();
          }
        }}
        style={{ marginRight: '10px', padding: '8px 16px' }}
      >
        删除用户
      </button>
      <button
        onClick={() => {
          if (confirm('确定要删除服务器吗?')) {
            handleDeleteServer();
          }
        }}
        style={{ padding: '8px 16px' }}
      >
        删除服务器
      </button>
    </div>
  );
}

export default ActionButtons;

方案二:自定义确认模态框(样式可控)

如果需要和项目UI风格统一,或者要实现更复杂的交互,就自己写一个可复用的确认模态框组件,灵活性更高。

第一步:创建可复用的确认模态框组件

import { useState } from 'react';

function ConfirmModal({ isOpen, message, onConfirm, onCancel }) {
  if (!isOpen) return null;

  return (
    <div style={modalOverlayStyle}>
      <div style={modalContentStyle}>
        <p>{message}</p>
        <div style={buttonContainerStyle}>
          <button onClick={onCancel} style={cancelButtonStyle}>
            取消
          </button>
          <button onClick={onConfirm} style={confirmButtonStyle}>
            确定
          </button>
        </div>
      </div>
    </div>
  );
}

// 样式可根据项目需求自定义调整
const modalOverlayStyle = {
  position: 'fixed',
  top: 0,
  left: 0,
  width: '100%',
  height: '100%',
  backgroundColor: 'rgba(0,0,0,0.5)',
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
};

const modalContentStyle = {
  backgroundColor: 'white',
  padding: '24px',
  borderRadius: '8px',
  boxShadow: '0 2px 10px rgba(0,0,0,0.2)',
};

const buttonContainerStyle = {
  marginTop: '16px',
  display: 'flex',
  justifyContent: 'flex-end',
  gap: '10px',
};

const cancelButtonStyle = {
  padding: '8px 16px',
  border: '1px solid #ccc',
  borderRadius: '4px',
  backgroundColor: '#fff',
  cursor: 'pointer',
};

const confirmButtonStyle = {
  padding: '8px 16px',
  border: 'none',
  borderRadius: '4px',
  backgroundColor: '#dc3545',
  color: 'white',
  cursor: 'pointer',
};

export default ConfirmModal;

第二步:在父组件中使用模态框

import { useState } from 'react';
import ConfirmModal from './ConfirmModal';

function ActionButtons() {
  const [modalState, setModalState] = useState({
    isOpen: false,
    message: '',
    onConfirm: () => {},
  });

  const handleDeleteUser = () => {
    console.log('用户已删除');
    setModalState({ ...modalState, isOpen: false });
  };

  const handleDeleteServer = () => {
    console.log('服务器已删除');
    setModalState({ ...modalState, isOpen: false });
  };

  const openConfirmModal = (message, confirmCallback) => {
    setModalState({
      isOpen: true,
      message,
      onConfirm: confirmCallback,
    });
  };

  return (
    <div>
      <button
        onClick={() => openConfirmModal('确定要删除用户吗?', handleDeleteUser)}
        style={{ marginRight: '10px', padding: '8px 16px' }}
      >
        删除用户
      </button>
      <button
        onClick={() => openConfirmModal('确定要删除服务器吗?', handleDeleteServer)}
        style={{ padding: '8px 16px' }}
      >
        删除服务器
      </button>

      <ConfirmModal
        isOpen={modalState.isOpen}
        message={modalState.message}
        onConfirm={modalState.onConfirm}
        onCancel={() => setModalState({ ...modalState, isOpen: false })}
      />
    </div>
  );
}

export default ActionButtons;

两种方案对比

  • 原生确认框:代码极简,无需额外开发,但样式固定无法修改,交互体验较基础。
  • 自定义模态框:可以完全匹配项目UI,支持添加更多交互细节(比如加载状态),但需要额外编写组件代码。

你可以根据项目的UI要求和复杂度选择合适的实现方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:52:29