[英]onChange in Material UI Menu component
thanks for being here!感谢您来到这里! My question is related to how I can create an 'onChange' property in the Material UI Menu component .
我的问题与如何在 Material UI Menu 组件中创建“onChange”属性有关。 When I am using the 'onChange' property of the Select component, I can easily alter my state after the user clicks on it.
当我使用Select组件的“onChange”属性时,我可以在用户单击它后轻松更改我的 state。 I would like to create a similar effect, but then using a Menu instead of a Select component.
我想创建一个类似的效果,但然后使用菜单而不是 Select 组件。 Note that I am using a function inside a hook, which might complicate things.
请注意,我在钩子内使用了 function,这可能会使事情复杂化。
Below I could show you how an example of how my code looks:下面我可以向您展示我的代码外观的示例:
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>;
That's my select component in action, which is working.那是我的 select 组件正在运行,它正在工作。 And here is the same Menu, where I don't know how to implement the "onChange":
这是相同的菜单,我不知道如何实现“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>;
I would be blessed if you could explain how to achieve a similar effect with the Menu component!如果您能解释如何使用 Menu 组件实现类似的效果,我会很幸运!
Thank you for reading.感谢您的阅读。
I think you should do that per MenuItem (at the onClick property).我认为您应该按照 MenuItem 执行此操作(在 onClick 属性中)。 The Menu itself doesn't have that kind of property: Material-UI page
菜单本身没有那种属性: Material-UI page
Secondly, I don't like value as a function.其次,我不喜欢 function 的价值。 I think you can just pass the variable (
sortHighestSummerTemp
or sortLowestWinterTemp
) to a state.我认为您可以将变量(
sortHighestSummerTemp
或sortLowestWinterTemp
)传递给 state。 React page reference反应页面参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.