I'm using the component MenuItem (material-UI) and I'm trying to choose an item when user press the 'tab' key, something like that:
{Object.keys(Countries).map(key => (
<MenuItem key={key} value={Countries[key]} onKeyDown={(ev) => {
if(ev.key === 'Tab') {
//How can I choose the selected item with tab key?
}
}}>
{Countries[key]}
</MenuItem>
))}
You need the menu item to have access to the change-handler for the Select. When a Tab occurs, it should send the menu item's value
to the change-handler in a similar manner as occurs on click -- via event.target.value
.
Below is a working example:
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import MenuItem from "@material-ui/core/MenuItem";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
container: {
display: "flex",
flexWrap: "wrap"
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200
},
dense: {
marginTop: 19
},
menu: {
width: 200
}
}));
const currencies = [
{
value: "USD",
label: "$"
},
{
value: "EUR",
label: "€"
},
{
value: "BTC",
label: "฿"
},
{
value: "JPY",
label: "¥"
}
];
const SelectOnTabMenuItem = React.forwardRef(
({ "data-value": valueForEvent, value, onChange, ...other }, ref) => {
const handleKeyDown = event => {
if (event.key === "Tab") {
event.persist();
// Getting the value from the "data-value" prop is necessary
// due to the manner in which Material-UI clones the MenuItem during
// display of the Select: https://github.com/mui-org/material-ui/blob/v4.5.1/packages/material-ui/src/Select/SelectInput.js#L226
event.target = { value: valueForEvent };
onChange(event);
}
};
return (
<MenuItem ref={ref} value={value} onKeyDown={handleKeyDown} {...other} />
);
}
);
export default function TextFields() {
const classes = useStyles();
const [values, setValues] = React.useState({
currency: currencies[0]
});
const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value });
};
const currencyHandleChange = handleChange("currency");
return (
<form className={classes.container} noValidate autoComplete="off">
<TextField
id="standard-select-currency"
select
label="Select"
className={classes.textField}
value={values.currency}
onChange={currencyHandleChange}
SelectProps={{
MenuProps: {
className: classes.menu
},
renderValue: option => option.label
}}
helperText="Please select your currency"
margin="normal"
>
{currencies.map(option => (
<SelectOnTabMenuItem
onChange={currencyHandleChange}
key={option.value}
value={option}
>
{option.label} ({option.value})
</SelectOnTabMenuItem>
))}
</TextField>
</form>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.