Перейти к контенту

Text Field (Текстовое поле)

Текстовые поля позволяют пользователям вводить и редактировать текст.

Текстовые поля позволяют пользователям вводить текст в интерфейсе. Обычно они появляются в формах и диалогах.

TextField

TextField представляет собой полноценный элемент управления формы, включая метку (label), само поле ввода и вспомогательный текст.

It supports standard, outlined and filled styling.

<form className={classes.root} noValidate autoComplete="off">
  <TextField id="outlined-basic" label="Outlined" />
  <TextField id="filled-basic" label="Filled" variant="filled" />
  <TextField id="standard-basic" label="Standard" variant="standard" />
</form>

Note: The standard variant of the TextField is no longer documented in the Material Design guidelines (here's why), but Material-UI will continue to support it.

Form props

Standard form attributes are supported e.g. required, disabled, type, etc. as well as a helperText which is used to give context about a field's input, such as how the input will be used.

Some important text

Some important text

Some important text

Validation

The error prop toggles the error state, the helperText prop can then be used to provide feedback to the user about the error.

Incorrect entry.

Incorrect entry.

Incorrect entry.

Multiline

The multiline prop transforms the text field into a textarea or a TextareaAutosize. Unless the rows prop is set, the height of the text field dynamically matches its content (using TextareaAutosize). You can use the rowsMin and rowsMax props to bound it.

Select (Список)

The select prop makes the text field use the Select component internally.

Please select your currency

Please select your currency

Please select your currency

Please select your currency

Please select your currency

Please select your currency

Иконки

There are multiple ways to display an icon with a text field.

Украшения поля ввода (Input)

The main way is with an InputAdornment. Например, вы можете использовать кнопку-иконку, чтобы скрыть или показать пароль. This can be used to add a prefix, a suffix or an action to an input.

Kg

Kg

Weight

$

Kg

Kg

Weight

$

Kg

Kg

Weight

$

Размеры

Fancy smaller inputs? Use the size prop.

The filled variant input height can be further reduced by rendering the label outside of it.

Расположение

dense and normal alter other styles to meet the specification. margin prop can be used to alter the vertical spacing of inputs. Using none (default) will not apply margins to the FormControl, whereas dense and normal will.

fullWidth can be used to make the input take up the full width of its container.

Full width!

Some important text

Some important text

Some important text

Full width!

Some important text

Some important text

Some important text

Full width!

Some important text

Some important text

Some important text

Uncontrolled vs Controlled

The component can be controlled or uncontrolled.

Компоненты

TextField состоит из более мелких компонентов ( FormControl, Input, FilledInput, InputLabel, OutlinedInput, и FormHelperText ) которые вы можете использовать напрямую, чтобы значительно кастомизировать ваши поля ввода.

Вы также могли заметить, что некоторые нативные свойства ввода HTML отсутствуют в компоненте TextField. Это сделано специально. Компонент включает в себя наиболее часто используемые свойства, а для расширенного использования можно использовать базовый компонент, показанный в следующей демонстрации. Вы все еще можете использовать inputPropsсвойства InputProps, InputLabelProps), если хотите избежать излишнего кода.

Some important helper text

Disabled

Error

Поля ввода

Цвет

The color prop changes the highlight color of the text field when focused.

Кастомизированные поля ввода

Ниже находятся примеры кастомизации компонента. You can learn more about this in the overrides documentation page.

Настройка не ограничивается CSS, вы можете использовать композицию для создания пользовательских компонентов и придать вашему приложению уникальный стиль. Ниже приведен пример использования компонента InputBase, вдохновленный Google Maps.


🎨 If you are looking for inspiration, you can check MUI Treasury's customization examples.

Ограничения

Сжатие

Состояние метки поля ввода (label) "shrink" не всегда корректно. Предполагается, что метка поля ввода уменьшается, как только в поле ввода что-нибудь отображается. В некоторых случаях мы не можем определить состояние "shrink" (числовое поле, поле даты, Stripe input). Вы могли заметить совпадения.

сжатие

Чтобы решить эту проблему, вы можете принудительно изменить состояние метки.

<TextField InputLabelProps={{ shrink: true }} />

или

<InputLabel shrink>Contagem</InputLabel>

Плавающая метка

Плавающий ярлык абсолютно позиционируется, он не повлияет на макет страницы. Необходимо убедиться, что поле ввода больше, чем метка для корректного отображения.

type="number"

Inputs of type="number" have potential usability issues:

  • Allowing certain non-numeric characters ('e', '+', '-', '.') and silently discarding others and silently discarding others and silently discarding others
  • Если вы составляете компонент:

and more - see this article by the GOV.UK Design System team for a more detailed explanation.

For number validation, one viable alternative is to use the default input type="text" with the pattern attribute, for example:

<TextField inputProps={{ inputMode: 'numeric', pattern: '[0-9]*' }} />

In the future, we might provide a number input component.

Helper text

The helper text prop affects the height of the text field. If two text fields are placed side by side, one with a helper text and one without, they will have different heights. For example:

Please enter your name

<TextField
  helperText="Please enter your name"
  id="demo-helper-text-misaligned"
  label="Name"
  variant="standard"
/>
<TextField
  id="demo-helper-text-misaligned-no-helper"
  label="Name"
  variant="standard"
/>

This can be fixed by passing a space character to the helperText prop:

Please enter your name

<TextField
  helperText="Please enter your name"
  id="demo-helper-text-aligned"
  label="Name"
  variant="standard"
/>
<TextField
  helperText=" "
  id="demo-helper-text-aligned-no-helper"
  label="Name"
  variant="standard"
/>

Интеграция с сторонними библиотеками текстовых полей

Вы можете использовать сторонние библиотеки для форматирования ввода. Вы должны предоставить пользовательскую реализацию элемента <input> со свойством inputComponent.

В следующем примере используются библиотеки response-text-mask и response-number-format. The same concept could be applied to e.g. react-stripe-element.

The provided input component should expose a ref with a value that implements the following interface:

interface InputElement {
  focus(): void;
  value?: string;
}
const MyInputComponent = React.forwardRef((props, ref) => {
  const { component: Component, ...other } = props;

  // implement `InputElement` interface
  React.useImperativeHandle(ref, () => ({
    focus: () => {
      // logic to focus the rendered component from 3rd party belongs here
    },
    // hiding the value e.g. react-stripe-elements
  }));

  // `Component` will be your `SomeThirdPartyComponent` from below
  return <Component {...other} />;
});

// usage
<TextField
  InputProps={{
    inputComponent: MyInputComponent,
    inputProps: {
      component: SomeThirdPartyComponent,
    },
  }}
/>;

Доступность

In order for the text field to be accessible, the input should be linked to the label and the helper text. The underlying DOM nodes should have this structure:

<FormControl>
  <InputLabel htmlFor="my-input">Адрес электронной почты</InputLabel>
  <Input id="my-input" aria-describedby="my-helper-text" />
  <FormHelperText id="my-helper-text">Мы никогда не распостраним ваш адрес.</FormHelperText>
</FormControl>
  • Если вы используете компонент TextField, вам просто нужно предоставить уникальный id.
  • Если вы составляете компонент:
<FormControl>
  <InputLabel htmlFor="my-input">Адрес электронной почты</InputLabel>
  <Input id="my-input" aria-describedby="my-helper-text" />
  <FormHelperText id="my-helper-text">Мы никогда не распостраним ваш адрес.</FormHelperText>
</FormControl>

Дополнительные проекты

Для более сложных вариантов использования вы можете воспользоваться: