owu*_*zan 4 javascript conditional-operator jsx reactjs next.js
如果索引号的余数为0,我想包装我需要在下面和下面显示的代码。我怎样才能做到这一点?我尝试了下面的方法,但没有成功。我收到语法错误。
{索引%3==0?...:...}
{索引% 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>
)
}
Run Code Online (Sandbox Code Playgroud)
ser*_*ays 10
在您的return语句中,您需要使用 JSX。JSX 中的条件可以采用不同的形式,以下是我更喜欢的形式:
如果存在(隐式&&):
{ arr.map( (item) => {
return(
item.condition &&
<div className="whatever">Your Content</div>
)
})}
Run Code Online (Sandbox Code Playgroud)
如果满足条件(条件为&&)
{ arr.map( (item, index) => {
return(
item.index % 3 &&
<div className="whatever">Your Content</div>
)
})}
Run Code Online (Sandbox Code Playgroud)
If/else 块(使用三元? () : ())
{ arr.map( (item, index) => {
return(
item.index % 3 ? (
<>
<div className="whatever">True catch condition</div>
<div className="whatever">Multiple HTML lines</div>
</>
) : (
<div className="whatever">False catch condition</div>
)
)
})}
Run Code Online (Sandbox Code Playgroud)
为了减少 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>
)
}
Run Code Online (Sandbox Code Playgroud)