You need to enable JavaScript to run this app. 如何实现选中表格行后,点击提交按钮发起API调用并在控制台展示数据
优惠活动
大模型
产品
解决方案
定价
更多

如何实现选中表格行后,点击提交按钮发起API调用并在控制台展示数据

表格行选中触发API调用的实现方案

核心交互流程落地

  • 状态层改造:在组件状态中新增选中行存储字段,替代当前无状态绑定的静态radio选择逻辑
  • 表格渲染优化:将硬编码在JSX中的行数据抽离为数组,统一渲染时给每个radio绑定选中变更事件,保证同一时间仅能选中一行
  • 提交逻辑绑定:给提交按钮绑定点击处理函数,首先校验选中状态,校验通过后调用目标接口,将返回结果打印到控制台

具体代码改造点

1. 新增组件状态与事件处理方法

// 初始化组件状态
constructor(props) {
  super(props);
  this.state = {
    // 存储当前选中的表格行数据,默认未选中
    selectedRow: null,
    // 表格源数据,后续可从后端接口拉取替换静态值
    tableDataSource: [
      {
        loadDate: "dfgrty",
        fileDate: "fgfg",
        service: "fgfg",
        provisionerCode: "erer",
        description: "uuio"
      }
    ]
  };
}

// 处理radio选中行的状态更新
handleRowChange = (rowItem) => {
  this.setState({ selectedRow: rowItem });
}

// 处理提交按钮点击,发起API请求
handleSubmitClick = async () => {
  const { selectedRow } = this.state;
  // 未选中行时直接中断流程,给出提示
  if (!selectedRow) {
    console.warn("请先选中表格中的一行");
    return;
  }
  try {
    // 发起目标地址的请求
    const apiResp = await fetch("https://mocki.io/v1/b512f8b8-64ab-46e4-9e0c-9db538a0ad9e", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(selectedRow)
    });
    const respData = await apiResp.json();
    // 将接口返回结果输出到控制台
    console.log("接口返回结果:", respData);
  } catch (error) {
    console.error("请求异常:", error);
  }
}

2. 改造render方法中的JSX绑定

render() {
  const { tableDataSource, selectedRow } = this.state;
  return (
    <div>
      <div
        className="table-employee"
        style={{ marginTop: "20px", border: " 1.5px solid darkgray" }}
      >
        <table className="table table-hover table-bordered table-sm">
          <thead>
            <tr>
              <th scope="col">Select</th>
              <th scope="col"> LOAD DATE</th>
              <th scope="col"> FILE DATE</th>
              <th scope="col"> SERVICE</th>
              <th scope="col"> PROVISIONER CODE </th>
              <th scope="col"> DESCRIPTION</th>
            </tr>
          </thead>
          <tbody>
            {tableDataSource.map((row, index) => (
              <tr key={index}>
                <td>
                  <input
                    type="radio"
                    name="selectRow"
                    checked={selectedRow === row}
                    onChange={() => this.handleRowChange(row)}
                  />
                </td>
                <td>{row.loadDate}</td>
                <td>{row.fileDate}</td>
                <td>{row.service}</td>
                <td>{row.provisionerCode}</td>
                <td>{row.description}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="btn-submit">
        <button
          className="btn btn-primary"
          style={{ marginRight: "30px" }}
          type="button"
          onClick={this.handleSubmitClick}
          disabled={!selectedRow}
        >
          submit
        </button>
      </div>
    </div>
  );
}

关键注意事项

  1. 原代码中按钮的type="submit"会触发默认表单提交行为导致页面刷新,修改为type="button"即可避免,无需额外绑定阻止默认事件的逻辑
  2. 原代码中直接写在radio标签上的preventDefault是无效属性,JSX中的默认行为阻止需要在对应事件处理函数中调用e.preventDefault()才能生效
  3. 接口请求的方法、传参格式可根据实际接口要求调整,GET请求可直接移除body字段,将参数拼接在接口地址后发起请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 19:54:07