我想在react js中创建嵌套元素,但是后续似乎不起作用。
var allSeats = [];
for( let i = 0 ; i<5 ; i++ ) {
allSeats.push( <div className="each-row"> );
for( let j=0; j<2 ; j++ ) {
allSeats.push( <div className="each-seat">hei</div> );
}
allSeats.push( </div> );
}
return (
<div className="theater">
{allSeats}
</div>
);
上述代码有什么问题?
答案 0 :(得分:1)
正如Fabian所说 - 必须关闭JSX元素:
必须使用自动关闭格式或使用a关闭所有标签 相应的结束标签 https://facebook.github.io/react/tips/self-closing-tag.html
拆分组件是否适用于您的预期用途?在这里演示:http://codepen.io/PiotrBerebecki/pen/ALabXK
class Rows extends React.Component {
render() {
var allRows = [];
for( let i = 0 ; i<5 ; i++ ) {
allRows.push( <div className="each-row">Row<Seats /></div> );
}
return (
<div className="theater">
{allRows}
</div>
);
}
}
class Seats extends React.Component {
render() {
var allSeats = [];
for( let j=0; j<2 ; j++ ) {
allSeats.push( <div className="each-seat">Seat</div> );
}
return (
<div className="seats">
<b>{allSeats}</b>
</div>
);
}
}
ReactDOM.render(
<Rows />,
document.getElementById('app')
);
答案 1 :(得分:1)
Piotr是对的 - 将代码拆分为组件要好得多。但为了以防万一,这里有固定的代码片段:
var rows = [];
for(let i=0; i<5; i++) {
var seats = [];
for(let j=0; j<2; j++) {
seats = seats.concat(<div className="seat"></div>);
}
rows = rows.concat(<div className="row">{seats}</div>);
}
return (
<div className="theater">
{rows}
</div>
);