【发布时间】:2021-12-08 03:18:03
【问题描述】:
我正在尝试围绕来自 MUI 的 Autocomplete 组件创建一个包装器
这是我的密码箱链接:https://codesandbox.io/s/typescript-material-ui-textfield-forked-j9xm3?file=/src/App.tsx:0-3149
出于演示目的,我已将 API 简化了很多。
我正在尝试使用这种 API 创建自己的多 Select 组件:
const Select = React.forwardRef(
({ children: c, onChange, value = [] }: SelectProps, ref) => {
...
const renderCheckbox = (props: any, option_component: any, value: any) => {
return (
<li>
<Checkbox checked={value.selected} {...props}>
{childrenToText(option_component.props.children)}
</Checkbox>
</li>
);
};
return (
<MuiAutocomplete
// open={true}
...
renderOption={renderCheckbox}
/>
);
}
);
const App = () => {
const [choices, setChoices] = useState([]);
return (
<Select
label="Favorite countries"
value={choices}
onChange={(newChoices: Array<string>) => setChoices(newChoices)}
>
<Option key="1" value="1" subheader={"Hot dogs"}>
United States
</Option>
<Option key="2" value="2" subheader={"Maple syrup"}>
Canada
</Option>
<Option key="3" value="3" subheader={"Tacos"}>
Mexico
</Option>
</Select>
);
};
为了实现这一点,我必须对孩子做一些花哨的事情并渲染我自己的自定义组件
我无法让 MUI 的自动完成组件与 MUI 的 FormControlLabel 和 Checkbox 组件一起使用。
只有当我在 MuiAutocomplete 上手动设置 open={true}(我的代码和框中的第 66 行)时,此 sn-p 才有效。
const Checkbox = ({ children, checked, ...rest }: any) => {
return (
<FormControlLabel
{...rest}
value={checked}
control={<MuiCheckbox checked={checked} />}
label={children}
/>
);
};
但是,当我注释掉 open={true} 时,它的行为方式就不一样了。
几个问题:
- 即使我设置了
disableCloseOnSelect={true},当我单击标签时下拉菜单也会关闭 - 我必须同时在
FormControlLabel上设置value={checked}和在MuiCheckbox上设置checked={checked},这感觉是多余的
【问题讨论】:
标签: reactjs typescript material-ui