Material UI TextField无法渲染HTML,求带内嵌标签边框的替代方案
解决方案
要实现带嵌入边框标签的只读HTML内容展示,可以通过Material UI的FormControl+InputLabel配合自定义容器div来实现,既保留TextField的样式效果,又能正确渲染HTML:
步骤1:自定义样式匹配TextField外观
使用makeStyles定义样式,模仿Outlined TextField的输入框样式:
import { makeStyles } from '@material-ui/core/styles'; import FormControl from '@material-ui/core/FormControl'; import InputLabel from '@material-ui/core/InputLabel'; import { useState } from 'react'; const useStyles = makeStyles((theme) => ({ formControl: { width: '100%', }, contentWrapper: { padding: theme.spacing(2, 1.5), border: `1px solid ${theme.palette.grey[300]}`, borderRadius: theme.shape.borderRadius, minHeight: theme.spacing(12), // 对应原TextField rows={5}的高度 whiteSpace: 'pre-wrap', overflowWrap: 'break-word', backgroundColor: theme.palette.grey[50], // 只读状态背景色 transition: theme.transitions.create(['border-color', 'box-shadow']), '&:hover': { borderColor: theme.palette.grey[400], }, '&.Mui-focused': { borderColor: theme.palette.primary.main, boxShadow: `0 0 0 2px ${theme.palette.primary.main}20`, }, }, }));
步骤2:构建组件实现样式与HTML渲染
用FormControl作为容器,InputLabel实现嵌入边框的标签,自定义div渲染HTML内容:
function MissionDisplay({ account }) { const classes = useStyles(); const [isFocused, setIsFocused] = useState(false); return ( <FormControl variant="outlined" className={classes.formControl} > <InputLabel shrink={true}>Our Mission</InputLabel> <div className={`${classes.contentWrapper} ${isFocused ? 'Mui-focused' : ''}`} dangerouslySetInnerHTML={{ __html: account.mission }} tabIndex={0} onFocus={() => setIsFocused(true)} onBlur={() => setIsFocused(false)} /> </FormControl> ); }
关键说明
FormControl的variant="outlined"会自动处理InputLabel的位置,让标签嵌入边框内,和原TextField效果完全一致。tabIndex={0}让容器可获取焦点,配合onFocus/onBlur状态切换,实现和原生TextField一致的焦点样式变化。dangerouslySetInnerHTML用于解析并渲染account.mission中的HTML内容,避免显示标签文本。- 自定义样式完全匹配Material UI的设计规范,保证视觉统一。
内容的提问来源于stack exchange,提问作者Jesse
相关产品推荐
相关产品推荐

