reactjs - 如何使材料 UI 的自动完成字段成为必需?
问题描述
我尝试了几种方法来使材料 UI 的自动完成字段类型成为必需,但我没有得到我想要的行为。我已经将我的领域封装在反应钩子形式中<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" />
解决方案
您可以使用以下逻辑来使其正常工作。虽然这可能不是最好的解决方案,但有效。
<Autocomplete
renderInput={(params) => (
<TextField
{...params}
label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label
required={value.length === 0}
/>
)}
/>
推荐阅读
- istio - envoy.filters.http.ext_authz 和 envoy.ext_authz 有什么区别?
- jmeter - 无法从响应中提取值并使用 JSON 提取器在下一个请求中使用它
- javascript - 在 html 和 javascript 中使用其他属性而不是 id
- sql - 查询失败 Oracle 但在 SQL Server 中工作
- java - Spring RestTemplate 收到“401 Unauthorized”
- machine-learning - BigQuery GCP 回归模型问题
- javascript - 如何共享一个对话框窗口以跨多个子组件加载不同的数据
- css - 为什么我尝试覆盖引导导航链接类在 next.js 中不起作用?
- python - Corey Schafer Django(第 3 部分):HTML 格式不正确
- c++ - 给定 N 作为输入,有没有一种方法可以在没有除法和没有三角的情况下生成常规 N 边形的角