材质UI的“选择”组件的值类型

时间:2020-07-29 08:22:36

标签: javascript reactjs typescript react-native material-ui

我正在使用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

为了对此进行调查,我尝试在typeof(criteria)函数中打印出showUsers。类型为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'而没有进行任何其他更改,则即使满足条件,这些条件也永远不会成立。

我要去哪里错了?可能是些小事。

1 个答案:

答案 0 :(得分:0)

我有个建议。 首先,您可以尝试使用switch代替if (criteria == '1') {,如果您这样使用它,Switch应该能够帮助您避免此问题:switch (Number(criteria)) {

这也将帮助您设置默认值,从而避免出现此错误:you have provided an out-of-range value 未定义 for the select component.