gpt4 book ai didi

javascript - ReactJS:如何水平渲染列

转载 作者:行者123 更新时间:2023-11-28 17:42:29 26 4
gpt4 key购买 nike

我遇到了一个问题,无法对获取的 API 数据的列进行水平排序。我正在尝试将从 API 获取的数据打印到表中。无论如何,行都可以很好地水平打印,但是我用于行的函数 this.state.data.map() 对于列的作用并不相同。我认为这是 ES6 标准,但我不确定。 Here is my printed issue.

这是我的代码示例:

class App extends React.Component
{
constructor()
{
super();
this.state = {
rows: [],
columns: []
}
}

componentDidMount()
{

fetch( "http://ickata.net/sag/api/staff/bonuses/" )
.then( function ( response )
{
return response.json();
} )
.then( data =>
{
this.setState( { rows: data.rows, columns: data.columns } );
} );

}


render()
{

return (
<div id="container" className="container">
<h1>Final Table with React JS</h1>
<table className="table">
<thead> {
this.state.columns.map(( column ) => (
<tr>

<th>{column[0]}</th>
<th>{column[1]}</th>
<th>{column[2]}</th>
<th>{column[3]}</th>
</tr>
) )}
</thead>
<tbody> {
this.state.rows.map(( row ) => (
<tr>
<td>{row[0]}</td>
<td>{row[1]}</td>
<td>{row[2]}</td>
<td>{row[3]}</td>
</tr>
) )
}
</tbody>
</table>
</div>
)
}
}


ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );

如果我为“th”元素赋予值,我就能够打印编码,但我想动态打印它,以防 API 中的数据已更改。

欢迎您直接向我的存储库做出贡献:Fetching API data into a table

Here is how looks like my example, when columns values has been hardcoded within 'th' elements.

如有任何建议,我们将不胜感激!

最佳答案

var data = {
columns: [
"Full name",
"Job title",
"Age",
"Bonus",
],
rows: [
[
"John Smith",
"team lead front-end",
30,
444.08,
],
[
"Tom Jones",
"front-end developer",
25,
333.3,
],
[
"Deborah Barnes",
"front-end developer",
21,
233.66,
],
[
"Isaac Roberson",
"technical support",
44,
353,
],
[
"Josh Brown",
"team lead back-end",
35,
353,
],
[
"Chester Mckinney",
"back-end developer",
33,
223.27,
],
[
"Ora Burton",
"back-end developer",
32,
192.92,
],
[
"Jim Brown",
"technical support",
19,
98.99,
],
],
}

class App extends React.Component
{
constructor()
{
super();
this.state = {
rows: [],
columns: []
}
}

componentDidMount()
{


this.setState( { rows: data.rows, columns: data.columns } );

}


render()
{

return (
<div id="container" className="container">
<h1>Final Table with React JS</h1>
<table className="table">
<thead>
<tr>
{this.state.columns.map(( column, index ) => {

return (<th>{column}</th>)
}
)
}
</tr>
</thead>
<tbody> {
this.state.rows.map(( row ) => (
<tr>
<td>{row[0]}</td>
<td>{row[1]}</td>
<td>{row[2]}</td>
<td>{row[3]}</td>
</tr>
) )
}
</tbody>
</table>
</div>
)
}
}


ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

希望对你有帮助

关于javascript - ReactJS:如何水平渲染列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com