[英]How to add <script> js include to the closing </body> tag in React?
[英]react.js every nth item add opening tag or closing tag
我在這個邏輯上遇到了問題,因為 react/jsx 不允許將非結束標記添加到數組/子組件中。 例如,對於 bootstrap css,我想為每4 列添加一行。
所以邏輯如下:
添加一個開頭的行 ex: <div className="row">
,然后在該行內循環,每個循環附加一個列 ex: <div className="column>{this.data}</div>
當循環達到 4 檢查使用if(i % 4 == 0)
並添加結束</div>
標記,同時添加新行標記<div className="row">
;
work in another language but in react this is not doable since we push a closing tag and a opening tag (which is invalid jsx):下面的代碼用另一種語言工作,但在 React 中這是不可行的,因為我們推送了一個結束標簽和一個開始標簽(這是無效的 jsx):
generateColumns(columns) {
let newColumns = [];
columns.forEach(function(column, idx) {
newColumns.push( <div className="column"> some data </div> );
if (idx % 4 == 0) {
// Here we end the row and start a new row, works in any other language.
newColumns.push( </div> <div className="row"> );
}
});
// This array now has the proper tags for opening a row every 4th item and closing it.
return newColumns;
},
render() {
return (
<div className="row">
{this.generateColumns(this.props.columns)}
</div>
)
}
預期輸出將是:
<div class="row">
<div class="column">
Some data
</div>
<div class="column">
Some more data
</div>
<div class="column">
Other data
</div>
<div class="column">
Something else
</div>
</div>
<div class="row">
<div class="column">
Some data
</div>
<div class="column">
Some more data
</div>
<div class="column">
Other data
</div>
<div class="column">
Something else
</div>
</div>
//the above would be repeated and new rows would appear every 4 columns.
render() {
const rows = array_chunk(this.props.columns, 4)
return (
{
rows.map((row) => (
<div className="row">
{
row.map((col) => (
<div className="col">{ col }</div>
))
}
</div>
))
}
)
}
一個示例 array_chunk(我建議你使用 lodash)
module.exports = function chunks(arr, size) {
if (!Array.isArray(arr)) {
throw new TypeError('Input should be Array');
}
if (typeof size !== 'number') {
throw new TypeError('Size should be a Number');
}
var result = [];
for (var i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, size + i));
}
return result;
};
我實際上只是使用了數組,並且反應很好地處理了渲染。
render() {
let rows = [],
cols = []
let index = 0
const totalCols = 20;
for (index; index < totalCols; index++) {
cols.push(<div class="col" key={index}/>)
if ((index + 1) % 4 == 0) {
rows.push(
<div class="row" key={index}>
{cols}
</div>
)
cols = []
}
}
return (
<div class="container">
{rows}
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.