【发布时间】:2020-07-29 08:22:36
【问题描述】:
我正在使用 Material UI 的 Select 组件(类似于下拉菜单),如下所示:
const [criteria, setCriteria] = useState('');
...
let ShowUsers = () => {
console.log('Working criteria', typeof(criteria));
const where: UserFilter = {};
if (criteria == '1') {
loadUsers({
variables: {
where: where,
},
});
}
if (criteria == '2') {
if (searchItem) {
where.firstName_contains = searchItem;
loadUsers({
variables: {
where: where,
},
});
}
}
}
...
return(
<Select
value={criteria}
onChange={event => setCriteria(event.target.value as string)}
//onChange={event => setCriteria(event.target.value)}
displayEmpty>
<MenuItem disabled value="">
<em>Search By</em>
</MenuItem>
<MenuItem value={1}>All</MenuItem>
<MenuItem value={2}>First Name</MenuItem>
</Select>
<Button onClick={() => ShowUsers()}>Search
</Button>
)
目前这给了我一个警告
Expected '===' and instead saw '==' eqeqeq
为了调查这个问题,我尝试在showUsers 函数中打印出typeof(criteria)。类型为number。
因此,我更改了(criteria === 1) 等。但随后它给出了This condition will always return 'false' since the types 'string' and 'number' have no overlap.ts 的错误。但是两者都已经是数字了,所以我不太明白。
此外,我还尝试过这样的更改:
const [criteria, setCriteria] = useState<number>();
..
onChange={event => setCriteria(Number(event.target.value))}
但是,我收到以下新警告:
you have provided an out-of-range value `undefined` for the select component.
Consider providing a value that matches one of the available options or ''.
The available values are ``, `1`, `2`.
Warning: A component is changing an uncontrolled input of type hidden to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
如果我只是简单地使用criteria === '1' 而不更改任何其他内容,那么即使它们应该是,也永远不会满足条件。
我哪里错了?可能是小事。
【问题讨论】:
标签: javascript reactjs typescript react-native material-ui