React基于布尔值实现元素条件渲染 可折叠Accordion组件开发求助
核心开发调整点
- 状态管理替换:你当前定义的
isExpanded是普通常量,修改后无法触发组件重渲染,需替换为React状态钩子 - 展示文本动态切换:增加展开状态判断,切换展示完整内容/截断内容,同时补充短文本场景的适配(内容本身少于40字符时不需要加省略号,也可以隐藏展开按钮)
- 容器高度动态适配:将展开状态作为props传入styled组件,控制
Accordion高度自动切换,替换写死的56px高度 - 交互体验优化:补充Chevron旋转动画、flex布局适配、无障碍支持等细节
完整优化后代码
// @flow import { useState } from 'react'; import styled from "styled-components"; import chevron from "../Assets/chevron-icon.svg"; type Props = { attribute: AttributeType, className?: string }; const Accordion = styled.div` background-color: #e5e9eb; min-height: ${props => props.$isExpanded ? '112px' : '56px'}; width: 612px; border-radius: 2px; border: 1px solid #27282a; margin-bottom: 48px; display: flex; align-items: center; padding: 0 12px 0 24px; box-sizing: border-box; span { overflow-wrap: break-word; margin-right: 12px; } `; const Chevron = styled.img` height: 40px; width: 40px; margin-left: auto; cursor: pointer; transform: ${props => props.$isExpanded ? 'rotate(180deg)' : 'rotate(0)'}; transition: transform 0.2s ease; `; const ExpandableString = ({ attribute, className }: Props) => { // 注意:如果实际参数是attribute.readonly请自行修改取值 const fullDescription = attribute?.readonlyvalue ?? ''; const shortHeading = fullDescription.substring(0, 40) + '...'; const [isExpanded, setIsExpanded] = useState(false); // 文本过短时不需要展开功能 const canExpand = fullDescription.length > 40; const showText = isExpanded ? fullDescription : (canExpand ? shortHeading : fullDescription); const toggleContent = () => { if (canExpand) setIsExpanded(prev => !prev); }; return ( <Accordion className={className} $isExpanded={isExpanded}> <span>{showText}</span> {canExpand && <Chevron onClick={toggleContent} onKeyDown={(e) => e.key === 'Enter' || e.key === ' ' ? toggleContent() : null} src={chevron} alt="Expand or collapse content" role="button" tabIndex={0} $isExpanded={isExpanded} />} </Accordion> ); }; export default ExpandableString;
额外优化建议
- 如果你的内容长度可能超过112px的两倍高度,可以把
min-height的展开值改成auto,同时给span加上下padding,自适应内容高度 - 可以通过props自定义截断字符数,不用写死40,提升组件复用性
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

