Pus*_*dav 6 reactjs material-ui react-hook-form
我尝试了几种方法来使材料 UI 的自动完成类型字段成为必需,但我没有得到我想要的行为。我已经将我的领域封装在 react hook 形式中,<Controller/>但没有运气。当没有向字段添加任何内容时,我想在提交时触发消息“字段是必需的”。
下面是代码片段,我没有删除注释,以便其他人更容易理解我之前遵循的方法 -
<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" />
Run Code Online (Sandbox Code Playgroud)
Nik*_*kos 14
您可以使用以下逻辑来使其工作。虽然这可能不是最好的解决方案,但确实有效。
<Autocomplete
renderInput={(params) => (
<TextField
{...params}
label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label
required={value.length === 0}
/>
)}
/>
Run Code Online (Sandbox Code Playgroud)
小智 8
我尝试使用文本字段中内置的必需内容进行自动完成,它的工作方式就像一个魅力。也许你可以用这个作为参考。
<Autocomplete
renderInput={(params) => {
<TextField {...params} required />
}
// Other codes
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4036 次 |
| 最近记录: |