我正在尝试创建一个将连续呈现3个项目描述的组件。
我有两个组件,一个是创建一个名为Project
的项目,我已经在下面添加了另一个代码。
我的主要问题是
1:如何在行开始前插入
<div class="row">
元素
2:怎么样 在行结束时结束
此代码正常运行但所有项目都在一行中呈现。
var React = require('react'),
projectData = require('./../../projects.json'),
Project = require('./project'),
projectLength = projectData.projects.length,
itemsInRow = 3,
clicked = 0; //Increment this number and rerender this cimponent on click and we are almost done
var Projects = React.createClass({
render: function() {
var projectsDOM = < div >
< div className = "jumbotron" >
< div className = "container" >
< h1 > Projects < /h1>
< /div>
< /div>
< div className = "container" >
< div className = "row" >
{projectData.projects.reverse().map(function(project, i) {
if(i < (clicked + 1) * itemsInRow) {
return <Project id={project.id} />
}
})}
< /div>
<hr/>
< /div>
< /div>
return projectsDOM;
}
});
module.exports = Projects;
答案 0 :(得分:1)
我担心没有声明性的方法 - 你必须用projectData.projects
对Array.slice()
数组切片然后为每个新创建的数组输出< div className = "row" > /*map the chunk of array like you already do*/</div>
答案 1 :(得分:1)
jalooc的回答帮助我思考正确的方向。因此,我将创建新行的职责交给了不同的组件,并传递了一组对象进行渲染。这是我的最终解决方案:
var React = require('react'),
projectData = require('./../../projects.json'),
ProjectsRow = require('./projects_row'),
itemsInRow = 3,
projects = projectData.projects.reverse();
var Projects = React.createClass({
getInitialState: function() {
return {
rows: [projects.splice(0, itemsInRow)]
}
},
loadMoreProjects: function(e) {
e.preventDefault();
var addRow = this.state.rows;
if(projects.length) {
addRow.push(projects.splice(0, itemsInRow));
this.setState({rows: addRow});
}
},
render: function() {
return (
< div >
< div className = "jumbotron" >
< div className = "container" >
< h1 > Projects < /h1>
< /div>
< /div>
< div className = "container" >
{this.state.rows.map(function(row, i) {
return <ProjectsRow row={row} key={i} />
}.bind(this))}
< /div>
< div className = "container" >
<a className="btn btn-default"
onClick = {this.loadMoreProjects}
role="button" > Load More </a>
</div>
< /div>
);
}
});
module.exports = Projects;