我正在try 创建以下文本字段,使其在MUI中如下所示:

enter image description here

然而,我有以下几点:

enter image description here

当我在文本字段内部单击时,占位符将滑动到顶部并放置在边框内,但我希望使其看起来像占位符位于框本身左上角的第一个图像.

我正在使用MUI的TextField组件:https://mui.com/material-ui/react-text-field/

有谁能解释一下这件事吗?

以下是我的代码:

CustomField.jsx

import React from "react"
import { styled } from "@mui/material/styles"
import TextField from "@mui/material/TextField"

const StyledTextField = styled(TextField)(({ width, marginTop }) => ({
  width: width || "343px",
  marginTop: marginTop || "25px",
  "& .MuiOutlinedInput-root": {
    "&:focus-within fieldset": {
      borderColor: "black",
      color: "black",
    },
  },
  "&:focus-within .MuiFormLabel-root": {
    color: "black",
  },
}))

const CustomTextField = ({ label, variant, helperText, value, onChange, disabled, width, marginTop }) => (
  <StyledTextField
    label={label}
    variant={variant}
    helperText={helperText}
    value={value}
    onChange={onChange}
    disabled={disabled}
    width={width}
    marginTop={marginTop}
  />
)

export default CustomTextField

App.jsx

const App = () => {
 const handleEmailChange = () => {};
 const email = "user@email.com;

 return (
   <CustomTextField
        label="Phone number or email"
        variant="outlined"
        helperText="Some helper text."
        onChange={handleEmailChange}
        value={email}
      />
 )
}

推荐答案

你应该用variant="filled"而不是variant="outlined".

然后,您可以创建自定义组件(或覆盖主题中的填充样式)以包括所需的边框/轮廓:

const FilledOutlinedInputField = styled((props) => (
  <TextField
    {...props}
    InputProps={{
      ...props.InputProps,
      disableUnderline: true,
    }}
    variant="filled" />
))(({ theme }) => ({
  '& .MuiFilledInput-root': {
    overflow: 'hidden',
    borderRadius: 4,
    backgroundColor: theme.palette.mode === 'light' ? '#FFF' : '#333',
    border: `2px solid ${ theme.palette.mode === 'light' ? '#F0F0F0' : '#000' }`,
    transition: theme.transitions.create([
      'border-color',
      'background-color',
      'box-shadow',
    ]),
    '&:hover': {
      borderColor: theme.palette.mode === 'light' ? '#08F' : '#FF0',
    },
    '&.Mui-focused': {
      backgroundColor: 'transparent',
      boxShadow: `${alpha(theme.palette.primary.main, 0.25)} 0 0 0 2px`,
      borderColor: theme.palette.primary.main,
    },
  },
}));

文档中有一个使用Reddit风格的输入字段的工作示例:https://mui.com/material-ui/react-text-field/#customization

Javascript相关问答推荐

为什么在集内和集外会产生不同的promise 状态(使用Promise.race)?

JavaScript文本区域阻止KeyDown/KeyUp事件本身上的Alt GR +键组合

没有输出到带有chrome.Devtools扩展的控制台

在页面上滚动 timeshift 动垂直滚动条

硬币兑换运行超时

Msgraph用户邀请自定义邮箱模板

CheckBox作为Vue3中的一个组件

如何从HTML对话框中检索单选项组的值?

在forEach循环中获取目标而不是父对象的属性

连接到游戏的玩家不会在浏览器在线游戏中呈现

如何使用JS创建一个明暗功能按钮?

Jest toHaveBeenNthCalledWith返回当前设置的变量值,而不是调用时的值

expo 联系人:如果联系人的状态被拒绝,则请求访问联系人的权限

无法设置RazorPay订阅API项目价格

MongoDB中的嵌套搜索

本地损坏的Java脚本

按特定顺序将4个数组组合在一起,按ID分组

rxjs在每次迭代后更新数组的可观察值

有没有办法在R中创建一张具有多个色标的热图?

如果我将高度设置为其内容的100%,则在Java脚本中拖动以调整面板大小时会冻结