[英]Autocomplete Set Default Value in React
I need to have a default value in my autocomplete in my react app.我需要在我的反应应用程序中的自动完成中有一个默认值。 My problem is when i try to submit it, it still is invalid.
我的问题是当我尝试提交它时,它仍然无效。 Meaning it has no value in it.
这意味着它没有任何价值。 I need to click the autocomplete and select it again just to make to have the value.
我需要再次单击自动完成和 select 以使其具有价值。
Pls check this codesandbox link CLICK HERE请检查此代码框链接点击这里
<Autocomplete
name="member_status"
value={values.member_status}
options={memberStatuses ? memberStatuses : []}
getOptionLabel={(memberStatus) => memberStatus.name}
onChange={(e, value) => {
setFieldValue(
"member_status",
value !== null ? value.id : ""
);
}}
renderInput={(params) => (
<TextField
{...params}
label="Member Status"
name="member_status"
variant="outlined"
onBlur={handleBlur}
helperText={
touched.member_status ? errors.member_status : ""
}
error={
touched.member_status && Boolean(errors.member_status)
}
/>
)}
/>
The issue here is you are setting the initial value of your Autocomplete
as an object
, then you're validating for a string
.这里的问题是您将
Autocomplete
的初始值设置为object
,然后您正在验证string
。
Changing your validationSchema
to将您的
validationSchema
架构更改为
const validationSchema = yup.object().shape({
member_status: yup
.object()
.shape({
id: yup.number(),
name: yup.string()
})
.nullable()
.required("Select member status")
});
and your Autocomplete
's onChange
handler to和你的
Autocomplete
的onChange
处理程序
...
onChange={(e, value) => {
setFieldValue("member_status", value); // set the new value to an object, not string
}}
should work.应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.