【问题标题】:onChange in Material UI Menu component材质 UI 菜单组件中的 onChange
【发布时间】:2021-02-24 11:46:25
【问题描述】:

感谢您来到这里!我的问题与如何在 Material UI Menu component 中创建“onChange”属性有关。当我使用Select 组件的'onChange' 属性时,我可以在用户单击它后轻松更改我的状态。我想创建一个类似的效果,但然后使用菜单而不是选择组件。请注意,我在钩子中使用了一个函数,这可能会使事情复杂化。

下面我可以向您展示我的代码的外观示例:

const [sortingMethod, setSortingMethod] = useState(() => sortHighestSummerTemp);

const onSortMethod = (e) => {
  setSortingMethod(e.target.value);
};

<FormControl>
  <InputLabel shrink>Sort By </InputLabel>{' '}
  <Select defaultValue="" onChange={onSortMethod}>
    <MenuItem value={() => sortHighestSummerTemp}>☀️ Hottest summers</MenuItem>
    <MenuItem value={() => sortLowestWinterTemp}>???? Coldest winters</MenuItem>
    <MenuItem value={() => sortMostHotDays}>???? Most hot days</MenuItem>
  </Select>
</FormControl>;

这是我的选择组件在运行,它正在工作。这是同一个菜单,我不知道如何实现“onChange”:

<FormControl className={classes.formControl}>
  <PopupState variant="popover" popupId="demo-popup-menu">
    {(popupState) => (
      <React.Fragment>
        <Button
          variant="contained"
          color="primary"
          startIcon={<SortIcon />}
          {...bindTrigger(popupState)}
        >
          Sort by
        </Button>
        <Menu
          value=""
          // onChange={onSortMethod} <-- How to do this? ⚠
          {...bindMenu(popupState)}
        >
          <MenuItem
            onClick={popupState.close}
            value={() => sortHighestSummerTemp}
          >
            ☀️ Hottest summers
          </MenuItem>
          <MenuItem
            onClick={popupState.close}
            value={() => sortLowestWinterTemp}
          >
            ???? Coldest winters
          </MenuItem>
          <MenuItem onClick={popupState.close} value={() => sortMostHotDays}>
            ???? Most hot days
          </MenuItem>
        </Menu>
      </React.Fragment>
    )}
  </PopupState>
</FormControl>;

如果你能解释一下如何用 Menu 组件实现类似的效果,我会很高兴的!

感谢您的阅读。

【问题讨论】:

    标签: reactjs material-ui material-design setstate


    【解决方案1】:

    我认为您应该按 MenuItem 执行此操作(在 onClick 属性中)。菜单本身没有那种属性:Material-UI page

    其次,我不喜欢将值作为函数。我认为您可以将变量(sortHighestSummerTempsortLowestWinterTemp)传递给一个状态。 React page reference

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2015-11-13
      • 1970-01-01
      • 2020-11-09
      • 2020-09-16
      • 1970-01-01
      相关资源
      最近更新 更多