在Reactstrap或Bootstrap中如何实现每行3张卡片,超出自动生成新行
适配实现方案
- 先修复参考代码的语法错误,将你的
products数组按每3个元素拆分为一个分组 - 调整渲染逻辑:外层遍历分组渲染
Row,内层遍历每个分组内的商品渲染Card,避免原来每个卡片单独套Row导致每行只有1张的问题
适配后完整代码(类组件render方法内)
render() { // 拆分products为每3个一组的二维数组 const productGroups = this.props.products.reduce((groups, product, index) => { index % 3 === 0 ? groups.push([product]) : groups[groups.length - 1].push(product) return groups }, []) return ( <Container> {/* 遍历每个分组渲染行 */} {productGroups.map((group, groupIdx) => ( <Row key={groupIdx}> <CardGroup> {/* 遍历分组内的商品渲染卡片 */} {group.map((product, productIdx) => ( <Card key={productIdx}> <CardImg top width="100%" src={`${process.env.PUBLIC_URL}/assets/images/1.jpg`} alt="Card image cap" /> <CardBody> <CardTitle tag="h5">{product.productName}</CardTitle> <CardSubtitle tag="h6" className="mb-4 text-muted"> author </CardSubtitle> <CardText>casdadasdx</CardText> </CardBody> </Card> ))} </CardGroup> </Row> ))} </Container> ) }
优化提示
- 循环的key优先使用商品的唯一id(比如
product.id)替换索引,避免React渲染警告 - 如需固定卡片宽度可给
Card添加style={{width: '18rem'}}属性,也可以套入Bootstrap的Col组件实现更灵活的响应式布局 - 不需要外层
Container可直接删除,匹配你现有项目的布局结构即可
内容的提问来源于stack exchange,提问作者codingmonster
相关产品推荐
相关产品推荐

