我有下面的代码,我试图找出如何将类别的映射数组转换为每个类别有四个类别的行。
renderCategories = () => {
const categories = this.state.categories.map( category => {
return (
<div key={ category.categoryId} className="col-sm-3 card text- center" style={{margin: '10px', paddingTop: '5px'}}>
<h5>
<Link to={ `/category/${ category.categoryId }`}>{ category.name }</Link>
</h5>
</div>
)
});
return categories;
};
答案 0 :(得分:0)
您需要使用“行”类将renderCategories包装到div中
renderCategories = () => {
const categories = this.state.categories.map( category => {
return (
<div key={ category.categoryId} className="col-sm-3 card text- center" style={{margin: '10px', paddingTop: '5px'}}>
<h5>
<Link to={ `/category/${ category.categoryId }`}>{ category.name }</Link>
</h5>
</div>
)
});
return <div class="row">{categories}</div>;
};
答案 1 :(得分:0)
要在每4列上创建一个新行,可以添加如下条件语句:
renderCategories = () => {
let categories = [];
this.state.categories.forEach((category, i) => {
if((i+1) % 4 == 0){
categories.push(
<div className="row" key={category.categoryId}>
<div key={category.categoryId} className="col-sm-3 card text- center" style={{ margin: '10px', paddingTop: '5px' }}>
<h5>
<Link to={`/category/${category.categoryId}`}>{category.name}</Link>
</h5>
</div>
</div>
)
}else{
categories.push(
<div key={category.categoryId} className="col-sm-3 card text- center" style={{ margin: '10px', paddingTop: '5px' }}>
<h5>
<Link to={`/category/${category.categoryId}`}>{category.name}</Link>
</h5>
</div>
);
}
});
return categories;
}
或者,您仍然可以通过插入
在一行中使用整列
每4项上的<div className="clearfix"></div>
强制列换行:
render() {
let categories = [];
this.state.categories.forEach((category, i) => {
categories.push(
<div key={category.categoryId} className="col-sm-3 card text- center" style={{ margin: '10px', paddingTop: '5px' }}>
<h5>
<Link to={`/category/${category.categoryId}`}>{category.name}</Link>
</h5>
</div>
);
// insert full width div every 4 columns
if ((idx + 1) % 4 === 0) { categories.push(<div className="clearfix"></div>) }
});
return categories;
}