如何在React中动态地将数据渲染到html表格中?

问题描述 投票:0回答:1

我正在尝试在 React 中渲染 html 表中的待办事项列表。我目前正在通过迭代每个待办事项的数据库行来执行此操作:

todoLogs.forEach(todoLog => {
        tableHtmlContent += `
          <tr>
            <td>${todos.find(x => x.id === todoLog.id).title}</td>
            <td><input type="checkbox" ${todoLog.d09_04_24 ? "checked" : "unchecked"}></input></td>
            <td><input type="checkbox" ${todoLog.d08_04_24 ? "checked" : "unchecked"}></input></td>
            <td><button onClick=${deleteTodo}><i class="material-icons">delete</i></button></td>
          </tr>
        `
      })

用它来更新保存模板字符串的变量:

  var tableHtmlContent = `
  <tr ref={tableHeaderContainer} className='border-2 border-black ml-2'>
    <th>Habit</th>
    <th>09/04</th>
    <th>08/04</th>
  </tr>
  `

并在表中渲染该变量:

<table
        className='mt-3 border-2 [&>tr]:border-2 [&>tr>td]:border-2 [&>tr>th]:border-2 [&>tr>th]:px-1 text-center'
        dangerouslySetInnerHTML={ { __html: tableHtmlContent}}
      >
      </table>

我现在需要做的是向表格中的按钮添加 onClick 功能,以允许我删除待办事项:

<button onClick=${deleteTodo}><i class="material-icons">delete</i></button>

- 但目前这不起作用,我收到错误:

async is not defined

除了按钮的问题之外,现在使用模板字符串执行此操作的方法似乎效率很低,所以我想知道是否有更好的方法来执行此操作?

这也是表格的样子:

enter image description heImage of the table

为了解决这个问题,我已经研究过:

  • 在反应中使用Ref

  • .innerHTML() 函数

  • useState()

  • useEffect()

-但找不到任何可行的东西。任何帮助将不胜感激?

javascript html reactjs asynchronous hook
1个回答
0
投票

在 React 中,您可以使用 JSX 语法与 JavaScript 逻辑相结合来映射数据并生成表格行和列,从而将数据动态渲染到 HTML 表格中。这是一个基本示例:

import React from 'react';

class DataTable extends React.Component {
  render() {
    // Sample data
    const data = [
      { id: 1, name: 'John', age: 30 },
      { id: 2, name: 'Jane', age: 25 },
      { id: 3, name: 'Bob', age: 35 }
    ];

    // Map over the data to generate table rows
    const tableRows = data.map((item) => (
      <tr key={item.id}>
        <td>{item.id}</td>
        <td>{item.name}</td>
        <td>{item.age}</td>
      </tr>
    ));

    // Render the table with the generated rows
    return (
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
          </tr>
        </thead>
        <tbody>
          {tableRows}
        </tbody>
      </table>
    );
  }
}

export default DataTable;

在此示例中:

  • 我们有一个
    DataTable
    组件可以呈现 HTML 表格。
  • render()
    方法中,我们定义样本数据。
  • 我们使用
    map()
    方法来迭代数据数组并动态生成表行(
    <tr>
    元素)。
  • 每行包含数据属性的表格单元格(
    <td>
    元素)。
  • 最后,我们使用
    return
    语句中生成的行来渲染表格。

您可以根据您的具体数据结构和要求自定义此方法。

© www.soinside.com 2019 - 2024. All rights reserved.