获取 React-Select 中突出显示选项的值

IT技术 reactjs react-select
2021-05-09 08:09:34

我正在使用带有异步选择组件的react-select v2

        <AsyncSelect
            cacheOptions
            components={{ Option }}
            loadOptions={this.getSearchItems}
            onInputChange={this.handleInputChange}
            placeholder="Search..."
            onKeyDown={this._handleKeyPress}
        />

如何访问因使用键盘上的向下键或鼠标悬停而突出显示的选项的值?

我想根据突出显示的选项触发重定向或 setState onKeyDown仅将输入值作为发送event.target.value

这是 Nordstrom 网站上的一个例子:

在此处输入图片说明

3个回答

我认为仅使用react-selectapi是不可能的,但是您可以创建自己的 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当用户选择选项时将调用该propshttps://stackblitz.com/edit/react-wpljbl

我通过使用 onChange props解决了它。

  1. 用户界面/选择组件

      class CustomSelect extends React.PureComponent<IProps> {
        handleChange = (selectedOption: any) => {
        if (this.props.onSelect) {
            this.props.onSelect(selectedOption);
        }
      };
    
      render() {
        const { data } = this.props;
        return (
          <Select
            onChange={this.handleChange}
            options={data}
          />
        );
      }
    

    }

    1. 我将 CustomSelect 与 react-router 4 一起使用的父级(我可以访问 withRouter)。

      class SelectParent extends React.Component<IProps> {
        onSelect = (option: any) => {
        const id = option.value;
        const { history } = this.props;
        history.push(`/category/${id}`);
      };
      
      render() {
        const { data } = this.props;
        return (
          <Select
          data={data}
          onSelect={this.onSelect}
        />);
        }
      }
      
      export default withRouter<any>(SelectParent);
      

那对我有用。

 handleOnChange = (value, { action }) => {
    if (action === 'select-option') {
      // do something
    }
  };


 render() {
   return (
     <Select onChange={this.handleOnChange} ... />
   )
 }