【问题标题】:How to make autocomplete field of material UI required?如何使材料 UI 的自动完成字段成为必需?
【发布时间】:2020-10-20 01:11:24
【问题描述】:

我尝试了几种方法来使材质 UI 的自动完成字段类型成为必需,但我没有得到我想要的行为。我已经将我的字段封装在反应钩子表单<Controller/> 中,但没有运气。当没有任何内容添加到字段时,我想在提交时触发消息“字段为必填项”。

下面是代码sn-p,我没有去掉cmets,这样其他人就更容易理解我之前采用的方法了-

  <Controller
        name="displayName"
        as={
          <Autocomplete 
                  value={lists}
                  multiple
                  fullWidth
                  size="small"
                  limitTags={1}
                  id="multiple-limit-lists"
                  options={moduleList}
                  getOptionLabel={(option) => option.displayName}
                  renderInput={(params,props) => {
                   return (
                      <div>
                        <div className="container">
                          <TextValidator {...params} variant="outlined" label="Display Name*" className="Display Text" 
                            name="displayName"  id="outlined-multiline-static" 
                            placeholder="Enter Display-Name" size="small"
        onChange={handleDisplay}
         // validators={['required']} this and below line does throw a validation but the problem is this validation stays on the screen when user selects something in the autocomplete field which is wrong.
        // errorMessages={['This field is required']} 
        // withRequiredValidator
        
                            />
                        </div>
                      </div>
                    )
                  }}
                  />
        }
        // onChange={handleDisplay}
        control={control}
        rules={{ required: true }}
        // required
        // defaultValue={options[0]}
        />
        <ErrorMessage errors={errors} name="displayName" message="This is required" />

【问题讨论】:

  • 它可能默认返回空对象,为什么不使用validate函数。

标签: reactjs material-ui react-hook-form


【解决方案1】:

您可以使用以下逻辑来使其正常工作。虽然这可能不是最好的解决方案,但很有效。

<Autocomplete 
    renderInput={(params) => (
        <TextField
            {...params}
            label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label 
            required={value.length === 0}
        />
    )}
/>

【讨论】:

    【解决方案2】:

    我尝试使用 textfield 中内置的 required 来自动完成,它就像一个魅力。也许你可以以此作为参考。

    <Autocomplete
        renderInput={(params) => {
            <TextField {...params} required />
        }
        // Other codes
    />
    

    【讨论】:

      【解决方案3】:

      由于您正在渲染&lt;TextValidator&gt;,因此您应该将强制(必需)属性应用于不在&lt;AutomComplete&gt; 上的组件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        • 2020-04-03
        • 2017-09-28
        • 1970-01-01
        相关资源
        最近更新 更多