首页 文章

Material-UI TextField - 将onChange应用于特定的TextField

提问于
浏览
0

我创建了一个通过对象数组“映射”的函数,并使用该信息创建材质-ui TextField元素 . 当用户输入的字符超过maxLength时,我试图输出错误消息 . 我想仅通过“onChange”显示用户当前正在使用的TextField的错误消息 . 但是,它正在应用于页面上的所有TextField . 你能帮我解决这个问题吗?

以下是我的两个功能:

这是displayCustomFields函数,它通过对象数组“映射”并将该信息用于TextField元素 .

displayCustomFields() {
    const { meteredConsumptionForm } = this.props.meteredConsumptionForm;
  
    if(Object.keys(meteredConsumptionForm).length > 0 ) {
      const customFields = meteredConsumptionForm.customfields;

      let customFieldPlaceholder = '';

      return (
        Object.keys(customFields).map((key, index) => {
          const customFieldItem = customFields[key];
          return (
            <div className="dd-form-text-field" key={index}>
             <TextField
                name="formTextField"
                className="metered-form-textfield"
                // id="first-textfield"
                id="metered-form-textfield-desc"
                // maxLength={10}
                margin="dense"
                fullWidth
                placeholder={customFieldPlaceholder}
                label={customFieldItem.label}
                onChange={this.handleTextChange.bind(this)}
                required={true}
                InputLabelProps={{
                  shrink: true
                }}
                inputProps={{
                  maxLength: 10,
                }}

                // error={false}
                error={this.state.textFieldError}
                helperText={this.state.textFieldErrorMsg}
             />
            </div>
          );
        })
      );
    }
  }

这是TextField的handleChange函数:

handleTextChange = () => {
    const el = document.getElementById('metered-form-textfield-desc');
    
    this.setState({
      textFieldValueLength: el.value.length
    });
    
    if(this.state.textFieldValueLength === el.maxLength-1) {
      console.log('Exceeded number of characters');
      this.setState({
        textFieldError: true,
        textFieldErrorMsg: 'Exceeded maximum number of characters'
      });
    } else if(this.state.textFieldValueLength !== el.maxLength) {
      this.setState({
        textFieldError: false,
        textFieldErrorMsg: ''
      });
    }
  }

2 回答

  • 1

    您只检查一个名为'metered-form-textfield-desc'的ID,因此所有文本字段都具有相同的ID

    const el = document.getElementById('metered-form-textfield-desc');
    

    你可以尝试这个只是添加键的值,这是索引(我假设这将使所有texfields唯一) . 感谢@Ted更正了id的值 .

    id={"metered-form-textfield-desc "+index}
    

    并通过将index传递给handleTextChange(index)方法并将其追加到同一位置来实现

    const el = document.getElementById('metered-form-textfield-desc '+index);
    
  • 1

    您可以将处理程序更改为: onChange={(e) => this.handleTextChange(e)}

    并在处理程序中:

    handleTextChange = (e) => {
        const el = e.target;
    

    那个'll get you the element that'目前正在改变而没有通过 id 查找

    Regardless which route you go, you do need to be sure to give them unique id's.

相关问题