javascript - 如何在带有 next.js 的数组映射函数中使用 if 语句
问题描述
如果索引号的余数为 0,我想包装我需要在下面和下面显示的代码。我怎样才能做到这一点?我尝试了下面的那些,但它没有用。我收到语法错误。
{索引% 3 == 0?...:...}
{index% 3 == 0 && ...}
export default function UserPosts() {
// some code...
return (
<div className={styles.userPosts}>
{postsList.map((post, index) => {
return (
if (index % 3 == 0) {
<div className={styles.userPostsRow}>
}
<div className={styles.userPostWrapper}>
<div className={styles.userPostColumn}>
<Link href={`/${username}`}>
<a>
<div className={styles.userPost}>
<img src={post.image} alt="" />
</div>
</a>
</Link>
</div>
</div>
if (index % 3 == 0) {
</div>
}
)
})}
</div>
)
}
解决方案
为了减少 JSX 重复,您可以将条件逻辑提取到将包装子组件的组件中。
const ConditionalWrapper = ({ children, condition }) => {
return condition ? (
<div className={styles.userPostsRow}>{children}</div>
) : (
children
)
}
export default function UserPosts() {
// some code...
return (
<div className={styles.userPosts}>
{postsList.map((post, index) => {
return (
<ConditionalWrapper condition={index % 3 == 0}>
<div className={styles.userPostWrapper}>
<div className={styles.userPostColumn}>
<Link href={`/${username}`}>
<a>
<div className={styles.userPost}>
<img src={post.image} alt="" />
</div>
</a>
</Link>
</div>
</div>
</ConditionalWrapper>
)
})}
</div>
)
}
推荐阅读
- r - 滞后不喜欢趋势
- sql - .NET Core - ExecuteSqlRaw - 最后插入的 id?
- html - 使用溢出向容器中的表添加行:自动增加容器的高度
- c# - 我如何检测 Windows 何时启动并使用 .Net / C# 捕获它?
- c# - 我如何显示我的列表
或 ComboBox 中的替代方案?(C#) - arrays - ReactJS - 如何将状态数据和函数从一个功能组件传递到另一个组件?
- r - 来自 htest 对象的索引值?
- javascript - 用js创建img元素并添加src属性
- mysql - SQL , 如何计算存款成功率?
- excel - Excel VBA / 宏以像 unix2dos 一样的“DOS”格式输出