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

React实现点击OOpen列时获取行与单元格ID并打印到控制台

解决方案:获取点击行的tr和第一个td的ID

嘿,作为React新手,遇到这个问题太正常啦~核心问题是你的openModal函数目前没有任何关于点击行的信息,所以我们需要把点击的上下文传递给它。这里有两种简单的实现方式:


方式一:通过事件对象动态获取(推荐,适合动态渲染的表格)

这种方式不需要硬编码ID,就算以后表格行是动态生成的也能正常工作:

  1. 修改openModal函数,接收事件参数,然后通过DOM API找到对应的元素:
openModal = (event) => {
  // 获取点击的td所在的tr元素
  const trElement = event.target.closest('tr');
  const trId = trElement.id;
  // 获取tr下的第一个td元素
  const firstTdElement = trElement.querySelector('td:first-child');
  const tdId = firstTdElement.id;

  // 输出到控制台
  console.log(`${trId} ${tdId}`);

  // 原有逻辑保持不变
  this.setState({ modalIsOpen: true });
  fetch(`https://jsonplaceholder.typicode.com/posts`)
    .then(results => results.json())
    .then(data => this.setState({ courses: data }))
    .catch(err => console.log(err));
};
  1. 修改表格里的onClick,把事件对象传递进去:
<tbody>
  <tr id="data1_tr">
    <td id="data1">1</td>
    <td onClick={(e) => this.openModal(e)}>OOpen</td>
  </tr>
  <tr id="data2_tr">
    <td id="data2">2</td>
    <td onClick={(e) => this.openModal(e)}>OOpen</td>
  </tr>
</tbody>

方式二:直接传递ID(适合静态硬编码的表格)

如果你的表格行是固定写死的,也可以直接把ID作为参数传给openModal:

  1. 修改openModal函数,接收两个参数:
openModal = (trId, tdId) => {
  // 直接输出传入的ID
  console.log(`${trId} ${tdId}`);

  // 原有逻辑保持不变
  this.setState({ modalIsOpen: true });
  fetch(`https://jsonplaceholder.typicode.com/posts`)
    .then(results => results.json())
    .then(data => this.setState({ courses: data }))
    .catch(err => console.log(err));
};
  1. 修改每个OOpen单元格的onClick,传入对应的ID:
<tbody>
  <tr id="data1_tr">
    <td id="data1">1</td>
    <td onClick={() => this.openModal('data1_tr', 'data1')}>OOpen</td>
  </tr>
  <tr id="data2_tr">
    <td id="data2">2</td>
    <td onClick={() => this.openModal('data2_tr', 'data2')}>OOpen</td>
  </tr>
</tbody>

完整修改后的代码示例(以方式一为例)

import React from "react";
import ReactDOM from "react-dom";
import Modal from "react-modal";
import './style.css';

Modal.setAppElement("#root");

class App extends React.Component {
  state = {
    modalIsOpen: false,
    courses: []
  };

  openModal = (event) => {
    // 获取tr和第一个td的ID
    const trElement = event.target.closest('tr');
    const trId = trElement.id;
    const firstTdElement = trElement.querySelector('td:first-child');
    const tdId = firstTdElement.id;
    
    console.log(`${trId} ${tdId}`);

    this.setState({ modalIsOpen: true });
    fetch(`https://jsonplaceholder.typicode.com/posts`)
      .then(results => results.json())
      .then(data => this.setState({ courses: data }))
      .catch(err => console.log(err));
  };

  closeModal = () => {
    this.setState({ modalIsOpen: false });
  };

  render() {
    return (
      <div className="App">
        <button type="button" className="modal-button" onClick={this.openModal}>
          Open Modal
        </button>
        <table>
          <thead>
            <tr>
              <td>Number</td>
              <td>Button</td>
            </tr>
          </thead>
          <tbody>
            <tr id="data1_tr">
              <td id="data1">1</td>
              <td onClick={(e) => this.openModal(e)}>OOpen</td>
            </tr>
            <tr id="data2_tr">
              <td id="data2">2</td>
              <td onClick={(e) => this.openModal(e)}>OOpen</td>
            </tr>
          </tbody>
        </table>
        <Modal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal}
          contentLabel="Demo Modal"
        >
          <h1>Modal Header</h1>
          <table>
            <thead>
              <tr>
                <th>Number</th>
                <th>Course name</th>
              </tr>
            </thead>
            <tbody>
              {this.state.courses.map(course => {
                return (
                  <tr key={course.id} id={course.userId}>
                    <td>{course.userId}</td>
                    <td>{course.title}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <button type="button" className="modal-button" onClick={this.closeModal}>
            Close
          </button>
        </Modal>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

(注:我还顺便给动态渲染的表格行加了key属性,这是React列表渲染的最佳实践哦~)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:22:34