我有一个带有复选框组件的Material UI自动完成组件。我怎样才能让它们都工作,这样只有当用户从自动完成中选择一个选项时,复选框才应该被选中。下面是我的组件的链接:
https://codesandbox.io/embed/material-demo-forked-of2cz?codemirror = 1
https://codesandbox.io/s/material-demo-forked-of2cz?from-embed=&文件=/demo.tsx
我终于让我的自动完成/复选框工作,并被默认选中(redux &ts)
const HIDDEN_USERS: HiddenUsersProps[] = store.getState().user.hiddenUsers
// array of objects
//{
// uid:"oKW8wDsasYdssdd1wTLggsas02"
// userName:"Matt"
//}
const [value, setValue] = useState<HiddenUsersProps[]>([])
//the only way i found to wait for the values from the redux store
useEffect(() => {
setValue(HIDDEN_USERS)
}, [HIDDEN_USERS])
const handleChange = (newValue: HiddenUsersProps[]) => {
setValue(newValue)
}
return (
<Autocomplete
options={HIDDEN_USERS}
value={value}
onChange={(_, newValue: HiddenUsersProps[]) => handleChange(newValue)}
getOptionLabel={(option: any) => option.userName}
isOptionEqualToValue={(option, value) => option.userName === value.userName}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox icon={icon}
checkedIcon={checkedIcon}
checked={selected} />
{option.userName}
</li>
)}
renderInput={(params) => (
<TextField {...params}
label="Hidden Users"
placeholder="Name"
variant="outlined" />)} />
)
"@mui/material": "^5.0.6",
你应该这样修改你的组件:
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import Checkbox from "@material-ui/core/Checkbox";
const options = ["Option 1", "Option 2"];
export default function ControllableStates() {
const [value, setValue] = React.useState<string | null>("");
const [inputValue, setInputValue] = React.useState("");
const [checked, setChecked] = React.useState<boolean>(false);
const [text1, setText1] = React.useState("");
const [text2, setText2] = React.useState("");
const isTextFieldsNotEmpty = text1.length > 0;
const handleFirstTextChange = (
event: React.ChangeEvent<HTMLInputElement>
) => {
setChecked(!checked)
setText1(event.target.value);
};
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : "null"}`}</div>
<div>{`inputValue: '${inputValue}' '${checked}' '${text1}'`}</div>
<br />
<Checkbox
checked={checked}
onChange={handleFirstTextChange}
inputProps={{ "aria-label": "primary checkbox" }}
/>
<Autocomplete
value={value}
onChange={(event: any, newValue: string | null) => {
setValue(newValue);
setChecked(!checked)
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
style={{ width: 300 }}
renderInput={(params) => (
<TextField
{...params}
onChange={handleFirstTextChange}
label="Controllable"
variant="outlined"
/>
)}
/>
</div>
);
}
我只是把setChecked放在同一个事件监听器比你的文本域。这将创建当用户选择一个字段时搜索的行为。