我认为仅使用react-select
api是不可能的,但是您可以创建自己的 HOC,将这个功能添加到 AsyncSelect。
class MyAsyncSelect extends React.Component {
/* Select component reference can be used to get currently focused option */
getFocusedOption() {
return this.ref.select.select.state.focusedOption;
}
/* we'll store lastFocusedOption as instance variable (no reason to use state) */
componentDidMount() {
this.lastFocusedOption = this.getFocusedOption();
}
/* Select component reference can be used to check if menu is opened */
isMenuOpen() {
return this.ref.select.state.menuIsOpen;
}
/* This function will be called after each user interaction (click, keydown, mousemove).
If menu is opened and focused value has been changed we will call onFocusedOptionChanged
function passed to this component using props. We do it asynchronously because onKeyDown
event is fired before the focused option has been changed.
*/
onUserInteracted = () => {
Promise.resolve().then(() => {
const focusedOption = this.getFocusedOption();
if (this.isMenuOpen() && this.lastFocusedOption !== focusedOption) {
this.lastFocusedOption = focusedOption;
this.props.onFocusedOptionChanged(focusedOption);
}
});
}
/* in render we're setting onUserInteracted method as callback to different user interactions */
render () {
return (
<div onMouseMove={this.onUserInteracted} onClick={this.onUserInteracted}>
<AsyncSelect
{...this.props}
ref={ref => this.ref = ref}
onKeyDown={this.onUserInteracted}
/>
</div>
);
}
}
然后,您可以以AsyncSelect
与焦点选项更改相同的方式使用此自定义组件:
class App extends React.Component {
onFocusedOptionChanged = focusedValue => console.log(focusedValue)
render() {
return (
<div>
<MyAsyncSelect
cacheOptions
loadOptions={loadOptions}
defaultOptions
onInputChange={this.handleInputChange}
onFocusedOptionChanged={this.onFocusedOptionChanged}
/>
</div>
);
}
}
工作演示:https : //stackblitz.com/edit/react-z7izuy
编辑:带有附加props的版本,onOptionSelected
当用户选择选项时将调用该props。
https://stackblitz.com/edit/react-wpljbl