首页 > 解决方案 > 反应不返回正确的ID

问题描述

我正在尝试用 react 编写一个动态表,但我不明白为什么我不能为按钮功能设置正确的 id。如果我单击按钮,它将返回所有记录的最后一个记录 id,如果我将按钮更改为不使用回调,它将返回正确的 id。

我正在传递需要从父组件返回的内容,如下所示:

  const tableContent = [
    {
      type: 'field',
      name: 'id'
    },
    {
      type: 'field',
      name: 'name'
    },
    {
      type: 'field',
      name: 'website'
    },
    {
      type: 'field',
      name: 'telephone'
    },
    {
      type: 'button',
      function: test,
      variables: ['id'],
      param: { variables: { id: '' }},
      iconClassName: "trash",
      icon: faEdit
    }
]

然后在我的表格组件中我这样做:

  const tableRows = table.map((record, index) => {
    let field = props.content.map((item, index) => {
      if (item.type == 'field') {
        return (
          <td key={index}>{getPropByString(record, item.name)}</td>
        )
      } else if (item.type == 'button') {
        item.param.variables.id = record.id
        return (
          <td key={index}>
            <button onClick={() => item.function(item.param.variables.id)}>test</button>
          </td>
        )
      }
    })
    return (
      <tr key={index}>{field}</tr>
    )
  })

测试功能是一个简单的控制台日志功能:

 const test = (a) => {
    console.log(a)
  }

标签: reactjs

解决方案


推荐阅读