【发布时间】:2019-10-18 11:51:22
【问题描述】:
我无法在我的 React 网页中动态生成多个“卡片”。我从 database.js 导入数据,但显然我没有正确实现 For 循环。
我已经在 render() 之外的函数中尝试了循环,但没有奏效。我需要 for 循环来生成数据库中的许多对象,但我被困在一个对象上。我可以在 thml 代码中调用 {} 中的数据,仅此而已。
projects.js
class Projects extends Component {
constructor(props) {
super(props);
this.state = { activeTab: 1 };
}
toggleCategories() {
if (this.state.activeTab === 1) {
for (let data of database) {
return (
<div className='projects-grid'>
<Card shadow={4} style={{ minWidth: '450', margin: 'auto' }}>
<CardTitle style={{height: '250px', background: data.image }}></CardTitle>
<CardText>
{data.name}
</CardText>
<CardActions border>
<Button colored>GitHub</Button>
<Button colored>Live Demo</Button>
</CardActions>
</Card>
</div>
)
}
}```
**database.js**
let database = [
{
name: 'Trombinoscope',
image: 'url(https://i.ibb.co/g4mT3K5/html-Css-Js.jpg)',
description: 'Group project',
languages: 'HTML, CSS, JavaScript'
},
{
name: 'CRUD System',
image: 'url(https://i.ibb.co/g4mT3K5/html-Css-Js.jpg)',
description: 'Video game database',
languages: 'PHP, SQL'
}
]
export default database;
Any help would be appreciated.
【问题讨论】:
-
你没有循环播放。您正在开始 一个循环,但随后在第一次循环迭代中执行
return,这将停止循环。toggleCategories应该渲染所有这些卡片吗? -
toggleCategories用于选择我要展示的项目类型。我会在某个时候添加一个 If 语句以仅显示有效数据,但我还没有做到这一点。
标签: javascript reactjs for-loop