如何在material-ui TextField中显示标签和占位符

Bri*_*ian 12 material-ui

在Material-UI (MUI) TextField中,我们可以同时拥有标签和占位符,但是当文本字段为空时,我们只能看到标签。我们必须开始编辑文本字段才能看到占位符。有没有办法说标签和占位符都应该在字段为空时首先显示?我们还希望占位符的样式略有不同,将其设置为与黑色标签文本颜色相比略为灰色。有没有办法做到这一点?

Pra*_*gam 24

您可以强制输入标签缩小。https://mui.com/components/text-fields/#shrink

您可以使用 TextField 上的 props 添加输入文本颜色sx。占位符也从输入文本颜色中获取颜色。您可以通过删除inputProps下面代码中的 props 来测试这一点。

如果您想要输入文本和占位符使用不同的颜色,请使用inputProps 参考:Styling the placeholder in a TextField

<TextField
  sx={{
    "& .MuiOutlinedInput-root": {
      color: "red"
    }
  }}
  variant="outlined"
  label="Your custom label"
  placeholder="Placeholder Text"
  InputLabelProps={{ shrink: true }}
  inputProps={{
    sx: {
      "&::placeholder": {
        color: "green"
      }
    }
  }}
/>
Run Code Online (Sandbox Code Playgroud)


Gen*_*ama 5

我仍在寻找最佳分辨率..

我目前的做法

<TextField focused label="Standard" placeholder='lorem ipsum' />
Run Code Online (Sandbox Code Playgroud)

或者

 <TextField  InputLabelProps={{ shrink: true }} label="Standard" placeholder='lorem ipsum' />
Run Code Online (Sandbox Code Playgroud)