这是关于:
https://github.com/paypal/downshift
我将onKeyDown
处理程序设置为可以识别Tab键的按下,并且能够正确获取highlightedIndex
的值,但是如何使用它来更改inputValue
?
import React from 'react'
import Downshift from 'downshift'
import {
Label,
Menu,
ControllerButton,
Input,
Item,
ArrowIcon,
XIcon,
css,
itemToString,
getItems,
} from '../shared'
class App extends React.Component {
render() {
return (
<div
{...css({
display: 'flex',
flexDirection: 'column',
marginTop: 50,
})}
>
<Downshift
onChange={selection =>
alert(
selection
? `You selected ${itemToString(selection)}`
: 'selection cleared',
)
}
itemToString={itemToString}
>
{({
getLabelProps,
getInputProps,
getToggleButtonProps,
getMenuProps,
getItemProps,
isOpen,
clearSelection,
selectedItem,
inputValue,
highlightedIndex,
}) => (
<div {...css({width: 250, margin: 'auto'})}>
<Label {...getLabelProps()}>Find a Star Wars character</Label>
<div {...css({position: 'relative'})}>
<Input
{...getInputProps({
isOpen,
placeholder: 'Enter a name',
**onKeyDown: event => {
console.log(event.key)
if (event.key === 'Tab') {
console.log(highlightedIndex)
}
},**
})}
/>
{selectedItem ? (
<ControllerButton
onClick={clearSelection}
aria-label="clear selection"
>
<XIcon />
</ControllerButton>
) : (
<ControllerButton {...getToggleButtonProps()}>
<ArrowIcon isOpen={isOpen} />
</ControllerButton>
)}
</div>
<div {...css({position: 'relative'})}>
<Menu {...getMenuProps({isOpen})}>
{isOpen
? getItems(inputValue).map((item, index) => (
<Item
key={item.id}
{...getItemProps({
item,
index,
isActive: highlightedIndex === index,
isSelected: selectedItem === item,
})}
>
{itemToString(item)}
</Item>
))
: null}
</Menu>
</div>
</div>
)}
</Downshift>
</div>
)
}
}
export default App
答案 0 :(得分:1)
我发现stateReducer在这种情况下会有所帮助。
stateReducer={(_, changes) => {
if (changes.type === Downshift.stateChangeTypes.blurInput) {
return {
...changes,
inputValue: your value,
isOpen: false
}
}
return changes
}}
与输入getInputProps.onKeyDown
事件配对
<Input {...getInputProps({
onKeyDown: event => {
switch (event.key) {
case 'Tab': {
// use the highlighted or first value
// update the state
break;
}
default:
break;
}
}
})} />