React条件渲染包裹SwiperSlide时出现JSX Unexpected token报错
问题原因
- 语法错误:JSX不允许单独渲染开放标签或者闭合标签。你之前测试用的
<p>start</p>是完整的闭合JSX元素,所以可以正常渲染;修改后你把<SwiperSlide>开放标签和</SwiperSlide>闭合标签拆分到两个独立的条件渲染分支中,JSX解析器无法识别不完整的标签结构,就会抛出你遇到的语法错误。 - 页面显示pager数值:你在JSX的花括号内写了赋值语句
{(pager = pager + 1)}、{pager === 3 ? (pager = 0) : ""},赋值表达式的返回值会被JSX直接渲染到页面上,这个问题和语法错误是独立的,但你的写法本身不符合React的渲染规范,不应该在返回的JSX中执行修改外部变量的副作用操作。
正确实现方案
要实现每3个条目包裹在一个SwiperSlide中,正确的做法是先把原始的alerts数组按每3个元素分块,再遍历分块后的数组,每个分块外层包裹完整的SwiperSlide标签,内层渲染3个条目,参考代码如下:
const Alerts = (props) => { const alerts = props.data; // 按每3个条目对数组分块 const chunkedAlerts = alerts.reduce((result, item, index) => { const chunkIndex = Math.floor(index / 3); if (!result[chunkIndex]) result[chunkIndex] = []; result[chunkIndex].push(item); return result; }, []); return ( <ul className={styles.alerts}> <Swiper spaceBetween={30} pagination={{ clickable: true }} className="mySwiper" > {chunkedAlerts.map((chunk, chunkIndex) => ( <SwiperSlide key={chunkIndex}> {chunk.map((e, index) => { const realIndex = chunkIndex * 3 + index; return ( <div key={realIndex} id={`alert-${realIndex}`} className={styles.alert}> <div className={styles.alert__content}> <div className={styles.alert__content_top}> <strong> {e.token} <a href={e.token_link}> <i className="fa fa-external-link"></i> </a> </strong> <span>{e.date}</span> </div> <div className={styles.alert__desc}>{e.description}</div> </div> <div className={styles.alert__type}>{e.type}</div> </div> ) })} </SwiperSlide> ))} </Swiper> </ul> ); };
内容的提问来源于stack exchange,提问作者user3630024
相关产品推荐
相关产品推荐

