簡體   English   中英

單擊時如何獲取表格相應單元格的值

[英]How to get value of corresponding cell of table on click

我正在使用react點擊HTML表我有一個HTML表,其中一個部分是可點擊的,我想在點擊該特定行的名稱時捕獲Id,然后打開新路由並將該值傳遞給其他開放的路線。

但是在這里我正在努力獲得相應的價值

我使名稱可點擊,並希望獲取該名稱的特定行 ID,然后將其傳遞

我的代碼

import React, { useState } from "react";
import "./styles.css";
import { useHistory } from "react-router-dom";

import "bootstrap/dist/css/bootstrap.min.css";

const App = () => {
  //const history = useHistory();
  const data = [
    {
      name: "mark",
      age: 25,
      gender: "Female",
      working: "No"
    },
    {
      name: "steve",
      age: 36,
      gender: "Male",
      working: "Yes"
    }
  ];
  const clickEvt = () => {
    alert("clickerd"); //here I want the age gender of clicked row
    //history.push("/employee_profile"); here I want to pass the data
  };
  return (
    <div className="App">
      <div className="table-responsive">
        <table className="table table-bordered">
          <thead className="table-secondary">
            <tr>
              <th>Name</th>
              <th>Age</th>
              <th>Gender</th>
              <th>Working</th>
            </tr>
          </thead>
          <tbody>
            {data.map(item => (
              <tr>
                <td>
                  <a onClick={clickEvt} className="linkValue">
                    {item.name}
                  </a>
                </td>
                <td>{item.age}</td>
                <td>{item.gender}</td>
                <td>{item.working}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default App;

代碼和框鏈接

  <a onClick={()=> clickEvt(item)} className="linkValue">
                    {item.name}
  </a>

然后,您可以使用 clickevnt 中的變量

 const clickEvt = (person) => {
    console.log('Got the age::',person.age);
  };

您可以將item傳遞給您的回調,例如...

 <a onClick={(e) => clickEvt(e, item)} className="linkValue">

至於將數據傳遞到新路由,您可以使用 reacts 內置上下文 API 或 redux 獲得全局 state。

然后,在重定向之前在全局 state 中設置所選配置文件,並在employee_profile 路由中從全局 state 檢索一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM