首页 > 解决方案 > 如何在带有 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>
    )
}

标签: javascriptreactjsnext.jsjsxconditional-operator

解决方案


为了减少 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>
    )
}

推荐阅读