reactjs - Material-UI Autocomplete onChange 不更新值
问题描述
我想onChange
在自动完成组件上使用事件来获取当前选定的值。问题是它没有按预期工作,所以当我单击检查/取消选中值复选框仍然未选中但在控制台中我可以看到添加了新值
取消注释这部分以使其工作:
value={myTempVal}
onChange={(event, newValue) => {
setMyTempVal(newValue);
console.log(newValue);
}}
在线演示: https ://codesandbox.io/embed/hardcore-snowflake-7chnc?fontsize=14&hidenavigation=1&theme=dark
代码:
const [myTempVal, setMyTempVal] = React.useState([]);
<Autocomplete
open
multiple
value={myTempVal}
onChange={(event, newValue) => {
setMyTempVal(newValue);
console.log(newValue);
}}
disableCloseOnSelect
disablePortal
renderTags={() => null}
noOptionsText="No labels"
renderOption={(option, { selected }) => {
return (
<>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.title}
</>
);
}}
options={option2}
// groupBy={option => option.groupName}
getOptionLabel={option => option.title}
renderInput={params => (
<div>
<div>
<SearchIcon />
</div>
<TextField
variant="outlined"
fullWidth
ref={params.InputProps.ref}
inputProps={params.inputProps}
/>
</div>
)}
/>
解决方案
您需要从函数中获取donors
receivers
和options
变量。这些变量在每次渲染时都会重新创建,这意味着它们的引用在每次渲染时都会发生变化,并且当自动完成进行引用相等检查以确定是否选择了一个选项时,他永远不会找到选择的选项。
const donors = [...new Set(data.map(row => row.donor))].map(row => {
return {
groupName: "Donors",
type: "donor",
title: row || "null"
};
});
const receivers = [...new Set(data.map(row => row.receiver))].map(row => {
return {
groupName: "Receivers",
type: "receiver",
title: row || "null"
};
});
const option2 = [...donors, ...receivers];
export const App = props => {
const [myTempVal, setMyTempVal] = React.useState([]);
return (
<Autocomplete
open
multiple
...
您还可以添加getOptionSelected
以覆盖参考检查:
<Autocomplete
open
multiple
disableCloseOnSelect
disablePortal
renderTags={() => null}
noOptionsText="No labels"
getOptionSelected={(option, value) => option.title === value.title}
renderOption={(option, { selected }) => {
return (
<>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.title}
</>
);
}}
options={option2}
// groupBy={option => option.groupName}
getOptionLabel={option => option.title}
renderInput={params => (
<div>
<div>
<SearchIcon />
</div>
<TextField
variant="outlined"
fullWidth
ref={params.InputProps.ref}
inputProps={params.inputProps}
/>
</div>
)}
/>
推荐阅读
- c# - 检查哪个数组的值为 0
- java - 为什么我使用大于 12.02 的 JAVAFX 版本会得到 GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
- javascript - 使用克隆元素将文件名传递给输入文本
- javascript - Mongoose 用于同一连接的多个模型
- postgresql - 使用 Terraform 在 AWS RDS PostgreSQL 上启用 PostGIS
- spring-boot - 通过使用 Docker-Compose 和 Spring Boot 运行的 IP 地址访问远程主机中的 Kafka
- ionic-framework - 未捕获(承诺):错误:无法匹配任何路由。URL 段:'tabs/tab1'
- python - 如何在 Python 中创建自定义类型验证函数?
- esper - esper 查询执行了一半——实际上只有一部分在运行
- json - 如何在没有占位符的情况下更改空手道 DSL 中文本响应的所有外观?