reactjs - 如何使用条件在页面上生成元素
问题描述
for (var k = 0; k < 10; k++) {
if (k % 2 === 0) {
weatherText = <div className="in_break">
}
weatherText += <div className="eachD" key={k}>
<div>
{
countIt === 0 ? (currDate.getHours() > 12 ? "Tonight" : "Today") : dayOfWeek[weekDay]
}
</div>
<div>
{
getDate
}
</div>
<div>
{
<ReturnIcon />
}
</div>
</div>
if (k % 2 === 0) {
weatherText += </div>
}
}
我要做的是eachD
在 `in_break' div 中按两个分组
但我不断得到:
Parsing error: Unexpected token 'weatherText = </div>'
这是布局:
in_break
eachD
eachD
in_break
eachD
eachD
in_break
eachD
eachD
...
请帮我解决我的问题
解决方案
更新
我希望这能满足您的需求:
setWeatherTextItems = (countId, currDate, dayOfWeek, weekDay, getDate) => {
// you make sure all the variables such like countId and currDate are available inside this function.
const items = [];
for (var k = 0; k < 10; k++) {
items.push(
<div className="eachD" key={k}>
<div>
{countIt === 0
? currDate.getHours() > 12
? "Tonight"
: "Today"
: dayOfWeek[weekDay]}
</div>
<div>{getDate}</div>
<div>{<ReturnIcon />}</div>
</div>
);
}
return items;
}
renderInBreak = () => {
const items = this.setWeatherTextItems();
const inBreakItems = [];
let breakBlock = [];
let newBreak = false;
items.forEach((textItem, index) => { //1
if(!newBreak) {
breakBlock.push(textItem);
if(index + 1 === items.length){
inBreakItems.push(breakBlock);
}
} else {
inBreakItems.push(breakBlock);
breakBlock = [];
breakBlock.push(textItem);
//without this condition check, the last element will be left out of an odd array length
if(index + 1 === items.length) {
inBreakItems.push(breakBlock)
}
}
if(index % 2) newBreak = true; //false
else newBreak = false; //false
});
return inBreakItems.map(twoTextWeatherItems => (
<div className="in_break">
{twoTextWeatherItems}
</div>
))
}
render(){
<div>
{this.renderInBreak()}
</div>
}
老的
React 应该以不同的方式处理事情,也许这会起作用:
在您的组件中定义一个方法来设置您的项目:
setWeatherTextItems = (countId, currDate, dayOfWeek, weekDay, getDate) => {
// you make sure all the variables such like countId and currDate are available inside this function.
const items = [];
for (var k = 0; k < 10; k++) {
items.push(
<div className="eachD" key={k}>
<div>
{countIt === 0
? currDate.getHours() > 12
? "Tonight"
: "Today"
: dayOfWeek[weekDay]}
</div>
<div>{getDate}</div>
<div>{<ReturnIcon />}</div>
</div>
);
}
return items;
}
在您的render
方法中,或者您愿意呈现这些项目的地方:
render(){
<div className="in_break">{this.setWeatherTextItems()}</div>
}
阅读有关如何在循环中渲染事物的更多信息。
您可以在 for 循环内或对您有意义的地方添加您想要的条件。
推荐阅读
- vuex - 无法读取未定义的 nuxtjs vuex 的属性“$axios”
- c++ - C++:从 .txt 文件中读取复数并存储到复数数组中
- parquet - Amazon Glue - 创建单个 Praquet
- java - @Transactional 的“REQUIRES_NEW”传播属性的真实世界用例是什么
- javascript - 在 Angular 运行时更改应用程序主题
- google-apps-script - 发送前将图像粘贴到电子邮件中,谷歌应用脚本
- php - 按列搜索超过 7,000 行并按列返回,
- swift - 使用 Kingfisher 时重新下载不同大小的图像
- emacs - 在组织乳胶导出中禁用标题
- progress-4gl - Progress 4gl 打印机不遵循输入的份数