为同一文本添加多种下划线样式的React组件开发需求
实现多样式下划线的React组件改造
需求说明
- 拼写错误:红色波浪下划线
- 有可用建议:橙色实线下划线
- 用户插入内容:绿色实线下划线
修改后的组件代码
export type TextType = "inserted" | "misspelled" | "unknown_word" | "Grammer_suggestion"; export interface CustomTextProps extends TypographyProps { label: string; type?: TextType; } export const CustomText = ({ label, type = "unknown_word", ...props }: CustomTextProps) => { // 类型与下划线样式的映射表 const typeStyleMap = { misspelled: { textDecorationColor: "red", textDecorationStyle: "wavy" }, Grammer_suggestion: { textDecorationColor: "orange", textDecorationStyle: "solid" }, inserted: { textDecorationColor: "green", textDecorationStyle: "solid" }, unknown_word: { textDecorationColor: "gray", textDecorationStyle: "solid" } }; const textStyles: SxProps = { textUnderlineOffset: "4px", textDecorationLine: "underline", textDecorationThickness: "3px", ...typeStyleMap[type] }; return ( <Typography variant="body2" sx={textStyles} {...props}> {label} </Typography> ); };
关键修改点
- 新增类型-样式映射表,将不同
TextType对应的下划线颜色、样式关联,避免冗余条件判断 - 给
type属性设置默认值unknown_word,处理未指定类型的场景 - 合并基础样式与类型专属样式,保证所有类型的下划线有统一的偏移量和粗细
- 移除冗余外层
div,直接返回Typography组件,减少DOM层级
使用示例
// 标记拼写错误文本 <CustomText label="teh" type="misspelled" /> // 标记有语法建议的文本 <CustomText label="go" type="Grammer_suggestion" /> // 标记用户插入的文本 <CustomText label="new content" type="inserted" />
内容的提问来源于stack exchange,提问作者DineshMsd
相关产品推荐
相关产品推荐

