React中map遍历判断当前index时if语句报expression expected如何解决
React TSX按索引差异化渲染报错问题解决
错误原因
- 你当前使用了箭头函数的隐式返回语法(
map((post,index) => (后面跟的圆括号代表直接返回括号内的内容),括号内仅允许放置表达式,if属于流程控制语句,不能直接放在表达式位置,因此触发expression expected错误。 - 额外注意:你写的
index=0是赋值操作,不是相等判断,逻辑判断需要写为index === 0。
正确实现方案
方案1:改隐式返回为显式返回(适配差异化结构复杂的场景)
给箭头函数加花括号,内部就可以正常写if等流程控制语句,最后用return返回对应结构即可:
export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ? this.props.recentNews.map((post, index) => { // 索引为0时返回特殊结构 if (index === 0) { return ( <a className={styles.singleNewsFirst} href={post.link} key={post.Title} > {/* 自定义的首条渲染结构 */} </a> ) } // 其他索引返回默认结构 return ( <a className={styles.singleNews} href={post.link} key={post.Title} > <div className={styles.singleNews__image} style={{ backgroundImage: `url(${post.image})` }} /> <div className={styles.singleNews__content}> <div className={styles.singleNews__content__info}> <span className={styles.singleNews__content__info__label}>{post.Featured}</span> <span className={styles.singleNews__content__info__date}> {post.date} </span></div> </div> <div className={styles.singleNews__content}> <div className={styles.singleNews__content__info}> <h2 className={styles.singleNews__content__info__title}> {post.Title} </h2> {post.likes ? ( <div className={styles.singleNews__content__info__reactions} > <span className={ styles.singleNews__content__info__reactions__likes } > <Icon iconName='Like' /> {post.likes} </span> <span> <Icon iconName='ActionCenter' /> {post.coments} </span> </div> ) : null} </div> </div> </a> ) }) : null} </> ) } }
方案2:用三元/短路表达式直接在JSX内判断(适配局部差异化的场景)
如果只是少量属性、局部结构有差异,不需要改返回结构,直接在JSX中嵌入表达式判断即可:
<a // 差异化类名 className={index === 0 ? styles.singleNewsFirst : styles.singleNews} href={post.link} key={post.Title} > {/* 首条额外加置顶标识 */} {index === 0 && <div className={styles.topBadge}>置顶</div>} {/* 其余原有公共结构 */} </a>
内容的提问来源于stack exchange,提问作者John John
相关产品推荐
相关产品推荐

