You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Material UI Typography点击展开隐藏文本问题求助

解决Material UI Typography多行省略点击展开的问题

你的思路问题分析

  • 切换className/m属性失效:Material UI内置样式优先级较高,自定义类如果没提升优先级(比如用!important或更具体的选择器)会被覆盖。
  • 控制WebkitLineClamp失败:仅修改该属性不够,必须配套设置display: -webkit-box、-webkit-box-orient: vertical、overflow: hidden这些属性,且要确保样式能正确作用到元素上。

可行方案

方案1:用sx属性结合state控制

直接通过sx属性根据状态动态设置样式,优先级更高,不会被内置类覆盖:

import { useState } from 'react';
import Typography from '@mui/material/Typography';

const TextExpand = ({ text }) => {
  const [expanded, setExpanded] = useState(false);

  return (
    <Typography
      onClick={() => setExpanded(!expanded)}
      sx={{
        cursor: 'pointer',
        display: '-webkit-box',
        overflow: 'hidden',
        WebkitBoxOrient: 'vertical',
        WebkitLineClamp: expanded ? 'unset' : 2,
        ...(expanded ? { whiteSpace: 'normal' } : {}),
      }}
    >
      {text}
    </Typography>
  );
};

export default TextExpand;

方案2:自定义Styled组件

用Material UI的styled API创建可控制展开的Typography组件,样式优先级足够:

import { useState } from 'react';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';

const ExpandableTypography = styled(Typography)(({ expanded }) => ({
  cursor: 'pointer',
  display: '-webkit-box',
  overflow: 'hidden',
  WebkitBoxOrient: 'vertical',
  WebkitLineClamp: expanded ? 'unset' : 2,
  ...(expanded && {
    whiteSpace: 'normal',
    WebkitLineClamp: 'none',
  }),
}));

const TextExpand = ({ text }) => {
  const [expanded, setExpanded] = useState(false);

  return (
    <ExpandableTypography
      expanded={expanded}
      onClick={() => setExpanded(!expanded)}
    >
      {text}
    </ExpandableTypography>
  );
};

export default TextExpand;

注意点

  • 若遇到-webkit-box-orient: vertical被CSS压缩工具移除的情况,可添加注释/* autoprefixer: off */强制保留该属性。
  • 若需要更友好的交互,可在文本旁单独添加IconButton控制展开状态,而非点击整个文本。

内容的提问来源于stack exchange,提问作者M_V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:42:34