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

antd Form多按钮处理:删除按钮onClick事件不触发怎么解决

问题修复方案

问题根因

  • 表单内按钮默认提交行为:原生<button>标签嵌入<form>结构时,若未显式指定type属性,默认是submit类型,点击会触发表单提交、页面刷新,导致日志还未输出控制台就被清空,绑定的逻辑也无法正常执行。
  • 回调参数命名冲突:删除按钮的onClick回调中,形参college实际是点击事件对象,覆盖了外层map遍历得到的学院名称变量,即便逻辑执行也拿不到目标学院值。
  • 额外优化点:原代码用普通变量count做序号,组件每次重渲染都会重置为1,改用map遍历的index生成序号更稳妥;同时给Option元素补充了React要求的唯一key属性,避免控制台警告。

修复代码

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Select, Button } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import CollegeList from "./CollegeList";

const { Option } = Select;

const Demo = () => {
  const collegesList = CollegeList;
  const [collegesSelectedList, setCollegesSelectedList] = React.useState([]);

  const handleRemoveList = (targetCollege) => {
    console.log("onClick", targetCollege);
    // 移除指定选中条目
    setCollegesSelectedList(collegesSelectedList.filter(item => item !== targetCollege))
  };
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  return (
    <Form name="validate_other" onFinish={onFinish}>
      <Form.Item name="select" label="Select">
        <Select
          placeholder="Please select a country"
          onChange={(college) => {
            setCollegesSelectedList([
              ...collegesSelectedList,
              collegesList[college].name
            ]);
          }}
        >
          {Object.keys(collegesList).map((college) => (
            <Option value={college} key={college}>{collegesList[college].name}</Option>
          ))}
        </Select>
      </Form.Item>
      <label>List of institutes selected</label>
      <div style={{ border: "1px solid #b3e2d2" }}>
        <Form.Item>
          {collegesSelectedList.map((college, index) => (
            <ul key={college}>
            <li >
              {index + 1}.{college}{" "}
              <Button
                size="small"
                // 显式指定为普通按钮,阻止默认提交行为
                htmlType="button"
                // 直接传入遍历得到的college变量,不要用形参覆盖
                onClick={() => handleRemoveList(college)}
                icon={<DeleteOutlined />}
                danger
              />
            </li>
            </ul>
          ))}
        </Form.Item>
      </div>

      <Form.Item
        wrapperCol={{
          span: 12,
          offset: 6
        }}
      >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, document.getElementById("container"));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:57:05