Javascript React.js从数组创建多个表
我一直在寻找解决问题的方法,但可能是因为我缺乏理解,所以什么都没用 我正在尝试使用React.js创建动态长度的表 在我的项目中,我使用返回JSON对象数组的库调用一个API,我们不知道返回数组的大小,但是对于数组中的每个JSON对象,我需要创建一个表并添加其数据。下面是API调用返回的一个示例Javascript React.js从数组创建多个表,javascript,html,reactjs,react-native,Javascript,Html,Reactjs,React Native,我一直在寻找解决问题的方法,但可能是因为我缺乏理解,所以什么都没用 我正在尝试使用React.js创建动态长度的表 在我的项目中,我使用返回JSON对象数组的库调用一个API,我们不知道返回数组的大小,但是对于数组中的每个JSON对象,我需要创建一个表并添加其数据。下面是API调用返回的一个示例 [ { "feedbackID": 12, "posterID": "John", "comment": "shortcomment" },
[
{
"feedbackID": 12,
"posterID": "John",
"comment": "shortcomment"
},
{
"feedbackID": 23,
"posterID": "billy",
"comment": "long comment"
}
]
因此,使用此返回,我必须创建两个表,一个在另一个下,如下所示:
| 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})
})
}
我根本不知道如何制作表格,我尝试了createElement
和Grid
,但我做得太错了,甚至无法编译代码。{this.state.feedback.map(item=>{
{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>
)
})}
返回(
反馈ID
{item.feedbackID}
海报ID
{item.posterID}
评论
{item.comment}
)
})}
在渲染方法中使用此选项应该可以:
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>;
}
renderable=()=>{
返回此.state.feedback.map(值=>{
返回(
反馈ID
{value.feedbackID}
海报ID
{value.posterID}
评论
{value.comment}
)
})
}
渲染(){
返回{this.renderable()};
}
Render方法主要是一个视图,因此建议将逻辑移到一个单独的方法。您需要一些css来处理外观。我现在不关心css,我现在只需要表格。如何在每个表格元素之间添加水平规则?我尝试在
之后添加
,但我得到了一个error@FBSTSUG我想你需要使用样式。返回语句html代码中的所有内容不是吗?@FBSTSUG它是JSX——一种类似html的语法,它被编译为Javascript。啊,好的,那么我该如何添加样式呢?很抱歉问了这么多糟糕的问题