【问题标题】:React.js create multiple tables from arrayReact.js 从数组创建多个表
【发布时间】:2018-05-20 06:31:00
【问题描述】:

我已经为我的问题寻找了解决方案,但可能因为我缺乏理解而没有任何效果。

我正在尝试使用 React.js 创建动态长度的表格。

我在我的项目中使用返回 JSON 对象数组的 axios 库调用 API,我们不知道返回数组的大小,但是对于数组中的每个 JSON 对象,我需要创建一个表并添加它的数据。以下是 API 调用返回的示例。

[

  {
        "feedbackID": 12,
        "posterID": "John",
        "comment": "shortcomment"
    },
    {
        "feedbackID": 23,
        "posterID": "billy",
        "comment": "long comment"
  }
]

因此,有了这个回报,我将不得不创建 2 个表,一个在另一个之下,如下所示:

| Feedback ID | 12           |
| Poster ID   | John         |
| Comment     | shortcomment |

| Feedback ID | 23           |
| Poster ID   | billy        |
| Comment     | long comment |

到目前为止,这是我的代码:

   export class ViewFeedback extends Component {
  constructor(props) {
    super(props)
    this.state = {
      feedback: []
    }
  }

  componentDidMount() {
    var id = this.props.match.params.id;

    // this returns the JSON array like shown above
    getfeedback(id).then((response) => {


     this.setState({feedback:response})

    })


  }

我完全不知道如何制作表格,我尝试了 createElementGrid 但我做错了,甚至无法编译代码。

【问题讨论】:

  • 你需要一些 CSS 来处理外观。
  • 我现在不关心 css 我现在只想要表格

标签: javascript html reactjs react-native


【解决方案1】:
{this.state.feedback.map(item => {
  return (
    <table>
      <tr>
          <td>Feedback ID</td>
          <td>{item.feedbackID}</td>
      </tr>
      <tr>
          <td>Poster ID</td>
          <td>{item.posterID}</td>
      </tr>
      <tr>
          <td>Comment</td>
          <td>{item.comment}</td>
      </tr>
  </table>
  )
})}

在你的渲染方法中使用它

【讨论】:

  • 如何在每个表格元素之间添加水平线?我尝试在&lt;/table&gt; 之后添加&lt;hr/&gt;,但出现错误
  • @FBSTUG 我猜你需要使用样式。
  • return 语句 html 代码中的所有内容都不是吗?
  • @FBSTSUG 这是 JSX - 一种类似 HTML 的语法,被编译成 Javascript。
  • 啊好吧,那我该如何添加样式呢?对不起,可怕的菜鸟问题
【解决方案2】:

这应该可行:

renderTable = () => {
    return this.state.feedback.map(value => {
        return (
            <table>
            <tr>   
                <td>Feedback ID</td>
                <td>{value.feedbackID}</td>
            </tr>
             <tr>   
                <td>Poster ID</td>
                <td>{value.posterID}</td>
            </tr>
             <tr>   
                <td>Comment</td>
                <td>{value.comment}</td>
            </tr>
        </table>
        )
    })
}

render () {
    return <div>{this.renderTable()}</div>;
}

渲染方法主要是一个视图,因此鼓励将逻辑移到单独的方法中。

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2014-09-25
    • 2014-01-24
    相关资源
    最近更新 更多