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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:57:20