Material UI:如何使TextField尺寸适配其占位符内容
Material UI TextField 自动适配占位符文本尺寸实现
在React框架的Material UI组件库中,要实现TextField组件尺寸自动适配其占位符文本大小,可参考以下实现代码及效果:
import * as React from "react"; import Box from "@mui/material/Box"; import TextField from "@mui/material/TextField"; export default function BasicTextFields() { setTimeout(() => { let el = document.getElementById("standard-basic"); console.log("Initial", el); }, 50); return ( <Box p={1}> <TextField sx={{ "& .MuiOutlinedInput-root": { color: "red" } }} variant="outlined" label="自定义标签" placeholder="Placeholder Text hahjhkjerh jhejr kjhejrh kjhasdh hjsadh " InputLabelProps={{ shrink: true }} inputProps={{ sx: { "&::placeholder": { color: "green" }, width: "fit-content" } }} /> </Box> ); }

关键实现说明
- 通过
inputProps.sx设置width: "fit-content",让输入框宽度自动适配占位符文本的实际宽度 - 自定义文本样式:将输入框内的文本颜色设为红色,占位符文本颜色设为绿色
- 配置
InputLabelProps={{ shrink: true }},使标签固定显示在输入框上方,避免干扰输入框的尺寸自适应逻辑
内容的提问来源于stack exchange,提问作者Santhosh
相关产品推荐
相关产品推荐

