我正在使用React with Material-ui和这里记录的Autocomplete组件- https://material-ui.com/components/autocomplete/ with downshift。
<Downshift id="downshift-options">
{({
clearSelection,
getInputProps,
getItemProps,
getLabelProps,
getMenuProps,
highlightedIndex,
inputValue,
isOpen,
openMenu,
selectedItem,
}) => {
const {onSelect, onBlur, onChange, onFocus, ...inputProps} = getInputProps({
onChange: event => {
if (event.target.value === '') {
clearSelection();
}
},
onSelect: event => {
if (event.target.id) {
this.props.onSelect(event.target.value);
}
},
onFocus: openMenu,
placeholder: 'Type to search',
});
return (
<div className={classes.container}>
{renderInput({
fullWidth: true,
classes,
label: "Assigned Rider",
InputLabelProps: getLabelProps({shrink: true}),
InputProps: {onBlur, onChange, onFocus, onSelect},
inputProps,
})}
<div {...getMenuProps()}>
{isOpen ? (
<Paper className={classes.paper} square>
{getSuggestions(this.props.suggestions, inputValue, {showEmpty: true}).map((suggestion, index) =>
renderSuggestion({
suggestion,
index,
itemProps: getItemProps({item: suggestion.label}),
highlightedIndex,
selectedItem,
}),
)}
</Paper>
) : null}
</div>
</div>
);
}}
</Downshift>
使用onSelect,我可以检索选择的值。我希望能够取回密钥。
function renderSuggestion(suggestionProps) {
const { suggestion, index, itemProps, highlightedIndex, selectedItem } = suggestionProps;
const isHighlighted = highlightedIndex === index;
const isSelected = (selectedItem || '').indexOf(suggestion.label) > -1;
return (
<MenuItem
{...itemProps}
key={suggestion.uuid}
value={suggestion.uuid}
selected={isHighlighted}
component="div"
style={{
fontWeight: isSelected ? 500 : 400,
}}
>
{suggestion.label}
</MenuItem>
);
}
在这里,我将uuid设置为每个选择的键。
我的最终目标是能够进行选择并检索uuid,而不是值本身。
虽然我可以使用返回的值来匹配一组条目,但我希望确保如果有任何重复的条目,它不会造成问题。
链接到我的完整代码的组件在这里- https://github.com/theocranmore/bloodbike/blob/master/react_app/src/components/UsersSelect.js#L143
谢谢!
发布于 2019-11-23 22:49:46
我不知道为什么你需要一个id,但是对于我自己来说,获取对象本身就足够了。
<Autocomplete .....
onChange={(event, newValue) => {
console.log(newValue); //this will give you the selected value dictionary (source)
}}
发布于 2020-06-02 16:45:54
您可以检索整个值,然后访问所需的密钥(option.id):
const options = [
{ id: 0, value: "foo" },
{ id: 1, value: "goo" },
];
<Autocomplete
options={options}
onChange={(event, option) => {
console.log(option.id); // 1
}}
renderInput={(params) => <TextField {...params} />}
/>;
https://stackoverflow.com/questions/58190710
复制