在React js中的TextField中放置长度约束

问题描述 投票:0回答:16
javascript reactjs event-handling react-router
16个回答
317
投票

您可以设置

maxLength
属性来限制文本框中的文本。

您可以将

onChange
传递给
maxLength
inputProps
material-ui(小写 i,而不是
I
nputProps)属性,而不是
TextField
方法。

<TextField
    required
    id="required"
    label="Required"
    defaultValue="Hello World"
    inputProps={{ maxLength: 12 }}
/>

基本上我们可以通过

inputProps
对象编辑所有输入元素的本机属性。

链接到TextField Api


46
投票

我找到了另一个解决方案这里

<TextField
    required
    id="required"
    label="Required"
    defaultValue="Hello World"
    onInput = {(e) =>{
        e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,12)
    }}/>

25
投票
    <TextField
      autoFocus={true}
      name="name"
      onChange={handleChange}
      placeholder="placeholder"
      id="filled-basic"
      variant="filled"
      size="small"
      fullWidth
      inputProps={{
        maxLength: 25,
      }}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            <SearchIcon />
          </InputAdornment>
        ),
      }}
    />

11
投票
      <TextField
        id="username"
        name="username"
        label={translate('username')}
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.username}
        error={Boolean(errors.username) && touched.username}
        helperText={(errors.username && touched.username && translate(errors.username))}
        required
        inputProps={{maxLength :20}}

      />

9
投票

值得注意的是,Material-ui

<TextField />
组件没有
maxlength
属性。然而,原始的 html
<input>
确实如此。因此,您实际上不需要创建任何额外的函数来使其正常工作。只需使用基本
<input>
属性即可使用
inputProps

实际答案是这样的:

inputProps={
    {maxLength: 22}
}
// Result => <input maxlength="yourvalue" />

它的作用是设置底层

maxlength
<input>
属性,结果是:
<input maxlength="yourvalue" />
。这里要注意的另一个重要事项是您使用
inputProps
而不是
InputProps
。您的目标是小写字母
inputProps


7
投票

如果您使用的是 MUI 5 版本

5.0.6
,由于对旧版本的支持,您将必须执行以下操作,

            <TextField
              id="standard-textarea"
              label="A label"
              placeholder="Some text here"
              multiline
              variant="standard"
              defaultValue={"Hello"}
              inputProps={{
                maxLength: 255,
              }}
              InputProps={{
                disableUnderline: true,
              }}
            />

TextField
同时支持
inputProps
InputProps
,但有些属性反之则不起作用。

maxLength
InputProps
中无法按预期工作,并且 MUI 5 的
disableUnderline
等属性在
inputProps
中无法按预期工作。

小心可能的

typo
i

请参阅 API 了解更多信息,https://mui.com/api/text-field/


6
投票

我发现 Material UI 中

TextField
Input
之间的行为有些奇怪

它们彼此非常相似,我看到的问题如下:

在 TextField 组件上,如果您使用大写

"I"
的 InputProps,则会显示装饰,但另一方面,如果您将其用作小写“
inputProps
”,则
maxLength
Html 属性将被视为
valid
,但不是
adorments

我最终使用

INPUT
而不是
TextField
,所以你可以在
 中使用 
adorments

               <TextField
                variant="outlined"
                required
                fullWidth
                error={errors.email}
                id="email"
                label={t("signup-page.label-email")}
                name="email"
                onChange={handleChange}
                inputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton aria-label="toggle password visibility">
                        <EmailIcon />
                      </IconButton>
                    </InputAdornment>
                  ),
                  maxLength: 120,
                }}
              />

在上面的代码中,

adorment
被忽略,但是
maxLength
被用作“
inputProps
”驼峰式大小写

下面的代码是一个工作示例,正如您所看到的,我将其视为旧样式中的

Form Control
、输入标签和输入“
outlinedInput

        <FormControl variant="outlined" fullWidth>
        <InputLabel htmlFor="firstName">Password</InputLabel>
        <OutlinedInput
          value={values.firstName}
          autoComplete="outlined"
          name="firstName"
          variant="outlined"
          required
          fullWidth
          error={errors.firstName}
          id="firstName"
          label={t("signup-page.label-firstname")}
          onChange={handleChange}
          autoFocus
          inputProps={{ maxLength: 32 }}
        />
      </FormControl>

解决方案。我的最后建议,使用

OutlinedInput
而不是
TextField
,这样你就可以分开放置
Adorments
maxLength

下面是一个带有

FormControl
OutlinedInput
inputProps
-
maxLength
和结束
Adorment
图标

的工作示例
      <FormControl variant="outlined" fullWidth>
        <InputLabel htmlFor="password">Password</InputLabel>
        <OutlinedInput
          value={values.passwordConfirm}
          variant="outlined"
          required
          fullWidth
          error={errors.passwordConfirm}
          name="passwordConfirm"
          label={t("signup-page.label-password-confirm")}
          type={values.showPasswordConfirm ? "text" : "password"}
          id="password-confirm"
          onChange={handleChange}
          inputProps= {{maxLength:32}}
          endAdornment= {
              <InputAdornment position="end">
                <IconButton
                  aria-label="toggle password visibility"
                  onClick={handleClickShowPassword("passwordConfirm")}
                  onMouseDown={handleMouseDownPassword}
                >
                  {values.showPasswordConfirm ? (
                    <Visibility />
                  ) : (
                    <VisibilityOff />
                  )}
                </IconButton>
              </InputAdornment>
          }
        />
        {errors.passwordConfirm && (
          <p className="error"> {errors.passwordConfirm} </p>
        )}
      </FormControl>

4
投票

接受的答案在 Firefox 中不适用于大数字(大于 16 位数字)。数字的行为方式很奇怪。

对于 22 长度的字段,我们最终使用了这个:

<TextField
  required
  validateOnBlur
  field="cbu"
  label="22 dígitos del CBU"
  validate={validate.required}
  type="text"
  inputProps={
    {maxLength: 22}
  }
  onInput={(e) => { e.target.value = e.target.value.replace(/[^0-9]/g, '') }}

/>

基本上,文本字段的原生

maxLength
约束,加上“即时”从字符串到数字的转换。

改进

此外,您可能更喜欢使其可重用且更具语义。

# constraints.js
const onlyNumbers = (e) => { e.target.value = e.target.value.replace(/[^0-9]/g, '') };

# form.js
<TextField
  field="cbu"
  label="22 dígitos del CBU" 
  inputProps={
    {maxLength: 22}
  }
  onInput={(e) => onlyNumbers(e) }

2
投票

材料设计

<TextField />
组件没有任何
length
属性。

您可以使用

onChange()
方法创建您的。

updateTextField(event,value){
  if(value.length <= 12){
     //Update your state
  }
  else{
    //Value length is biggest than 12
  }
}

<TextField
    id="SigninTextfield"
    label="Aadhaar number"
    id="Aadhar"
    lineDirection="center"
    required={true}
    type="number"
    onChange={(e,v) => this.updateTextField(e,v)}
    style={styles.rootstyle}
    erorText="Please enter only 12 digits number"
/>

1
投票

在您的更改处理程序中,只需编写即可。

if (event.target.value.length !== maxLength ) return false; 

1
投票

我也遇到了类似的问题,但使用的是 TextareaAutosize。不幸的是,

inputProps={{ maxLength: 12 }}

不适用于 TextareaAutosize。

以下解决方法适用于 TextareaAutosize 以及文本和数字。 受到此问题已接受答案的启发 - https://stackoverflow.com/a/49130234/5236534

onInput = {(e) =>{
    e.target.value = (e.target.value).toString().slice(0,10)

import * as React from 'react';
import TextareaAutosize from '@mui/material/TextareaAutosize';

export default function MinHeightTextarea() {
  return (
    <TextareaAutosize
      aria-label="minimum height"
      minRows={3}
      placeholder="Minimum 3 rows"
      style={{ width: 200 }}
      onInput = {(e) =>{
        e.target.value = (e.target.value).toString().slice(0,10)
    }}
        
    />
  );
}

演示链接:限制 MUI TextareaAutosize 中的字符长度


1
投票
<TextField
id="SigninTextfield"
label="Aadhaar number"
id="Aadhar"
lineDirection="center"
required={true}
type="number"
inputProps={{
maxLength: 20,
}}
style={styles.rootstyle}
erorText="Please enter only 12 digits number"
/>

1
投票

我们可以通过以下方式使用 inputProps 属性进行设置

import React from 'react'
import { Autocomplete, TextField } from '@mui/material'


export default function Select({
    onChangeInput,
    label,
    name,
    value,
    options,
    placeholder,
    disabled,
    error,
    helpertext,
    required,
    shrink,
    maxLength
}) {

    const _onChange = (e, v) => {
        onChangeInput(v)
    }

    return (
        <Autocomplete
            freeSolo
            fullWidth={true}
            multiple={false}
            margin={'noraml'}
            readOnly={disabled}
            name={name}
            isOptionEqualToValue={(option, value) => option.label === value.label}
            value={value}
            options={options}
            placeholder={placeholder}
            renderInput={params => (
                <TextField {...params}
                    label={label}
                    error={error}
                    required={required}
                    helperText={helpertext}
                    variant={'standard'}
                    inputProps={{ ...params.inputProps, maxLength: (maxLength && parseInt(maxLength)) || 99}}
                    InputLabelProps={{ shrink: shrink, style: { fontSize: 18 } }}
                />
            )}
            onInputChange={_onChange}
        />
    )
}

0
投票

对于仍在寻找数字字段解决方案的人来说,这个解决方案对我来说效果很好。

onInput={(e: any) => {
                  e.target.value = Math.max(0, parseInt(e.target.value))
                    .toString()
                    .slice(0, 2);
                }}

确保使用任意一个。


0
投票

import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";

export default function BasicTextFields() {
  const [num, setNum] = React.useState();
  const limitChar = 12;
  const handleChange = (e) => {
    if (e.target.value.toString().length <= limitChar) {
      setNum(e.target.value);
    }
  };

  return (
    <Box component="form">
      <TextField
        type="number"
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        onChange={(e) => handleChange(e)}
        defaultValue={num}
        value={num}
      />
    </Box>
  );
}


0
投票

其中很多答案现在已被弃用。推进 MUI 的新方法是使用 slotProps:

return (
    <TextField
        id={id}
        name={id}
        label={label}
        value={value}
        onChange={onChange}
        onBlur={onBlur}
        size={size}
        error={!!error}
        slotProps={{ htmlInput: { maxLength: 50 } }}
        {...props} />
);
© www.soinside.com 2019 - 2024. All rights reserved.