获取 React 中高亮选项的值-Select

Get value of highlighted option in React-Select

我正在使用 react-select v2 和异步 select 组件。

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

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

我想根据 highlighted 选项触发重定向或 setState。 onKeyDown 仅发送 输入值 作为 event.target.value.

以下是 Nordstrom 网站上的示例:

我认为仅使用 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

编辑: 带有附加道具 onOptionSelected 的版本,当用户选择选项时将调用该道具。 https://stackblitz.com/edit/react-wpljbl

我使用 onChange 道具解决了它。

  1. UI/Select分量

      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} ... />
   )
 }