Javascript 将长度限制放在 React js 的 TextField 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45939909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:16:20  来源:igfitidea点击:

Put length contraint in a TextField in react js

javascriptreactjsevent-handlingreact-router

提问by Mayank Bansal

I am taking an input from the user of the card number and wants that the length entered by user must not be less than and more than 12. Here is the declaration of my textfield.

我正在接受卡号用户的输入,并希望用户输入的长度不能小于或大于 12。这是我的文本字段的声明。

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

Now I am not understanding whether to use javascript or any event handler for restricting the length.

现在我不明白是否使用 javascript 或任何事件处理程序来限制长度。

回答by AlexKumar

You can set the maxLengthproperty for limiting the text in text box.

您可以设置maxLength限制文本框中文本的属性。

Instead of onChangemethod you can pass maxLengthto the inputPropsprops of material-uiTextField.

相反的onChange方法,你可以传递maxLengthinputProps的道具material-uiTextField

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

Basically we can edit all input element's native attrs via inputPropsobject.

基本上我们可以通过inputProps对象编辑所有输入元素的原生属性。

Link to TextFieldApi

链接到TextFieldApi

回答by Gaurav Bharti

I found another solution here.

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

<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)
    }}/>

回答by fahimeh ahmadi

      <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}}

      />

回答by GeraGamo

I discovered something weird on the behavior between TextFieldand Inputfrom Material UI

我发现了一些很怪的行为TextField,并Input从材料UI

They are very similar to each other, the problem I see is the following:

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

On the TextField component, if you use InputProps with capital "I", the Adorments are shown, but in the other hand if you use it as lowercase "inputProps", the maxLengthHtml attribute is TAKEN as valid, but not the adorments

在 TextField 组件上,如果您将 InputProps 与大写一起使用"I",则显示装饰,但另一方面,如果您将其用作小写的“ inputProps”,则maxLengthHtml 属性将被视为valid,但不是adorments

I ended up using INPUTinstead of a TextFieldso you can use adormentsin

最后我用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,
                }}
              />

in the above code the adormentis ignored, but maxLengthtaken used as "inputProps" camel case

在上面的代码中adorment被忽略,但maxLength被用作“ inputProps”驼峰案例

The below code is a working example, as you might see, I embraced it as in the old style within a Form Control, the input label and the input "outlinedInput"

下面的代码是一个工作示例,如您所见,我在 a 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>

Solution. My final recommendation, use an OutlinedInputinstead of a TextField, so you can put in a separated way Adormentsand also maxLength

解决方案。我的最终建议,使用 anOutlinedInput而不是 a TextField,这样您就可以分开放置Adorments,也可以maxLength

Below a working example with FormControlOutlinedInput, inputProps- maxLengthand an end AdormentIcon

在带有FormControlOutlinedInput, 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>

回答by Alexis

The material-design <TextField />component haven't any lengthproperty.

材料设计<TextField />组件没有任何length属性。

You can create yours in the onChange()method.

您可以在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"
/>

回答by mayid

The accepted answer won't work in Firefox for large numbers (greater than 16 digits). Numbers just behaves in a weird way.

对于大数字(大于 16 位),已接受的答案在 Firefox 中不起作用。数字只是以一种奇怪的方式表现。

For a 22 length field we ended up using this:

对于 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, '') }}

/>

/>

Basically, native maxLengthconstraint for text fields, plus a conversion from string to numbers "on the fly".

基本上,maxLength文本字段的本机约束,以及“动态”从字符串到数字的转换。

Improvement

改进

Also you may prefer to make this reusable and more semantic.

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

# 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) }