我试图将2d数组显示为表格,但我不完全确定如何使用React进行此操作。这段代码目前只输出第一行,我尝试将2d数组作为一个整体返回,但这也没有。
var DisplayRow = React.createClass({
getDefaultProps: function() {
return {
columns: []
};
},
render: function(){
console.log(this.props.columns);
var entries = []
for (var i = 0; i < this.props.columns.length; i++){
return(
<DisplayElement row={this.props.columns[i]} key={i} />
);
};
}
});
var DisplayElement = React.createClass({
getDefaultProps: function(){
return {
row: []
};
},
render: function(){
console.log(this.props.row);
var elements = []
for (var i=0; i < this.props.row.length; i++){
elements.push(<td> {this.props.row[i]} </td>);
}
return (
<tr> {elements} </tr>
)
}
});
答案 0 :(得分:3)
用更清晰的代码弄清楚:
var DisplayRow = React.createClass({
getDefaultProps: function(){
return {
columns: []
};
},
render: function(){
var rows = this.props.columns.map(function (item, i){
var entry = item.map(function (element, j) {
return (
<td key={j}> {element} </td>
);
});
return (
<tr key={i}> {entry} </tr>
);
});
return (
<table className="table-hover table-striped table-bordered">
<tbody>
{rows}
</tbody>
</table>
);
}
});
答案 1 :(得分:0)
可能是这样的,其中SnipsView是行,而SnipsListItem是列。
class SnipListItemRender extends React.Component {
render() {
let snipSpanColor = (this.props.index === this.props.selectedKey) ? '#b58900' : '#afac87';
return (
<div id='SnipDivSty' onclick={this.snipClickHandler} className="FlexBox" style={SnipDivSty}>
<div id='SelectSnipDivSty' style={SelectSnipDivSty}>
<JButton btn={selectSnipBtn} parentClickHandler={this.snipClickHandler} />
</div>
<span id='SnipSpanSty' style={{color: snipSpanColor, width: 'calc(70% - 142px)'}}>{this.props.snippet.snip}</span>
<JButton btn={SnipBtn} parentClickHandler={this.snipClickHandler} />
</div>
);
}
}
class SnipListItem extends SnipListItemRender {
snipClickHandler = (buttonid) => { Actions.selectSnipItem(this.props.snippet, buttonid); }
}
let _snipDataMap = function(snip, index) {
return (
<li id='SnipsDivLiSty' key={index} style={SnipsDivLiSty}>
<SnipListItem snippet={snip} index={index} selectedKey={this.props.selectedKey} />
</li>
);
}
export default class SnipsView extends React.Component {
render() {
let list = this.props.data.map(_snipDataMap, this)
return (
<div id='SnipsDivSty' style={SnipsDivSty}>
<ul id='SnipsDivUlSty' style={SnipsDivUlSty}>
{list}
</ul>
</div>
);
}
}
&#13;