使用React与CSS实现手风琴展开卡片时底部无法跟随内容扩展问题
问题根因
蓝色底部区域无法跟随内容同步扩展的核心原因是Footer样式中固定了高度值,固定高度会限制容器高度不会随内部内容动态变化,所以展开文本后容器不会自动撑开。
修复方案
1. 修复底部区域高度自适应
修改styles.js中Footer的样式,把固定height替换为min-height,保证默认状态高度为50px,内容增多时自动扩展:
const Footer = styled.div` background-color: rgb(242, 247, 251); width: 100%; /* 替换固定height为min-height */ min-height: 50px; font-size: 12px; line-height: 12px; color: #4f4f4f; display: flex; justify-content: center; flex-direction: column; align-items: center; cursor: pointer; /* 可选添加上下内边距,避免内容贴边 */ padding: 12px 0; .accodion { padding: 30px; } `;
2. 实现多卡片点击自动收起逻辑
如果需要支持多个卡片,展开当前卡片时自动收起其他已展开卡片,把原来布尔类型的expanded状态改为存储当前展开卡片的唯一标识即可,示例代码如下:
import { Card, Footer, Header } from "./styles"; import { useState } from "react"; // 示例卡片数据,可根据需求自行扩展 const cardList = [ { id: 1, lastViewed: "2024-01-01", content: "卡片1的lorem文本内容" }, { id: 2, lastViewed: "2024-01-02", content: "卡片2的lorem文本内容" }, { id: 3, lastViewed: "2024-01-03", content: "卡片3的lorem文本内容" } ]; export default function App() { // 存储当前展开的卡片id,null代表没有展开的卡片 const [expandedId, setExpandedId] = useState(null); return ( <> {cardList.map((card) => ( <Card key={card.id}> <Header>last viewed: {card.lastViewed}</Header> <Footer> <span onClick={() => { // 点击已展开卡片则收起,否则展开当前点击卡片 setExpandedId(expandedId === card.id ? null : card.id); }} > View Details </span> {expandedId === card.id && ( <div className="accodion">{card.content}</div> )} </Footer> </Card> ))} </> ); }
内容的提问来源于stack exchange,提问作者prashant padadune
相关产品推荐
相关产品推荐

