问题
I am trying to programmatically set focus on (activate) one of the MenuItem(s) inside the Menu component in material-ui. I can manually do it by tabbing to it but I need to do it programmatically in response to a key down event.
<Menu disableAutoFocus={true}>
<MenuItem .../>
<MenuItem .../>
...
</Menu>
回答1:
Do you mean by select the menuItem programmatically? If so, you can use the concept of 'controlled component'.
Here is the example, If this.state.selectedItem = 1, the item 'Maps' will be selected. If this.state.selectedItem = 2, the item 'Books' will be selected.
<Menu
selectedMenuItemStyle={ {backgroundColor: '#c00', color: '#FFFFFF'} }
value={this.state.selectedItem}
>
<MenuItem primaryText="Maps" value='1'/>
<MenuItem primaryText="Books" value='2' />
</Menu>
来源:https://stackoverflow.com/questions/41623914/how-to-set-focus-on-a-menuitem-in-material-ui