React中使用dangerouslySetInnerHTML时如何实现text-overflow省略号效果?
text-overflow: ellipsis 不会单独生效,必须同时满足对应的样式规则,你可以按下面的方案调整:
生效前置条件
- 元素必须设置
overflow: hidden - 单行省略需要额外设置
white-space: nowrap - 元素必须设置明确宽度,不能由内容撑开宽度
- 如果需要多行省略,需要使用webkit内核适配规则
代码调整示例
单行省略
const MyFeedList: IPost = MainData?.recentMyPostResponseList?.map((item: any) => { return ( <div className="feed" key={item.id}> <img src={item.postImage} width="500px" /> <h4>{item.postName}</h4> <h6 style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", width: "500px" // 和上方图片宽度保持一致即可 }} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(item.content), }} ></h6> </div> ); });
多行省略(以显示2行后省略为例)
适配绝大多数现代浏览器:
const MyFeedList: IPost = MainData?.recentMyPostResponseList?.map((item: any) => { return ( <div className="feed" key={item.id}> <img src={item.postImage} width="500px" /> <h4>{item.postName}</h4> <h6 style={{ overflow: "hidden", textOverflow: "ellipsis", display: "-webkit-box", WebkitLineClamp: 2, // 自定义显示行数 WebkitBoxOrient: "vertical", width: "500px", wordBreak: "break-all" // 兼容长文本/英文自动换行 }} dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(item.content), }} ></h6> </div> ); });
特殊情况处理
如果插入的富文本内容自带<p>、<div>等块级子元素导致省略失效,可以在DOMPurify配置中过滤块级标签转为行内标签,或者在样式中给内层子元素继承外层的省略规则即可。
当前错误效果参考:
内容的提问来源于stack exchange,提问作者sunpl13
相关产品推荐
相关产品推荐

