我正在尝试使用 React 和 React-Bootstrap 创建一个具有自定义表行数的表。该表应该存储有关某个视频游戏的玩家统计数据,并且根据视频游戏,统计数据可能会发生变化,因此行数和这些行的标题也必须能够动态变化。我想在保存当前统计信息列表的状态下创建一个数组,然后使用 map 函数将该数组映射到一个元素并渲染表格。但是,在尝试了几种方法之后,我无法获取任何要渲染的自定义输入。下面是代码:
class Statistics extends Component {
constructor(props) {
super(props)
this.state = {
game: '',
player_names: [],
positions: [],
stat_categories: [
'kills',
'deaths',
'assists'
]
}
}
renderTableRows(array) {
return (
<tr>
<th> NAME </th>
<th> TEAM </th>
<th> POSITION </th>
{ array.map(item => {
console.log(item)
<th key={item}> {item} </th>
})
}
</tr>
)
}
render() {
const columnLength = this.state.player_names.length
const statCols = this.state.stat_categories
return (
<div>
<MyNav url={this.props.location.pathname} />
<Table responsive striped bordered hover>
<thead>
{ this.renderTableRows(statCols) }
</thead>
</Table>
</div>
)
}
}
控制台还正确记录了状态数据(击杀、死亡、助攻)——因此问题出在渲染元素时。任何帮助将不胜感激!
最佳答案
您的 map 函数中的 renderTableRows
内没有 return 语句。
使用 ES6 箭头函数时,您可以:
不使用return语句直接返回数据
(args) => (returnedData);
或者添加一些逻辑而不是直接返回,
(args) => { // Logic here return returnedData }
在第二种情况下,您将需要一个 return 语句,因为您正在记录日志,如果您选择删除日志记录,请采用第一种方法。
此外,请将代码直接发布在您的问题中,因为使用图像会降低其可读性并且不会被搜索引擎索引。
关于javascript - 使用 React 动态创建表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51197205/