React-select scrollintoView 不滚动 selected 值

React-select scrollintoView does not scroll the selected value

我正在使用 react-select3.2.0。当我打开 select 框和 select 选项时。然后我再次打开我的 select 下拉列表,然后 selected 值出现在视图中。 但是当下拉菜单的值来自道具而不是通过打开下拉菜单手动 selected 时,问题就来了。然后,当我打开下拉菜单时,它不会滚动到 selected 值的视图中。 我也尝试过 react-select 的 menuScrollIntoView={true} 道具,但我的问题仍然存在。 我的 Select 组件如下;

import Select from "react-select";
.
.
.
    <Select 
      options={props.options}
      // isLoading={props.options ? true: false}
      onMenuOpen={onOpen}
      value={props.defaultOption}
      onChange={(event: any) => props.onSelect(event)}
      className ={"MyDropdown"}
      classNamePrefix={"MyDropdown"}
      // menuShouldScrollIntoView={true}
      isDisabled={props.isDisabled}
      isSearchable={props.isSearchable}
      >
    </Select>

通过查找所选索引

给出值属性
<Select options={options} value={options[selectedIndex]} />

所以我能够使用带有 timeOut 的 onMenuOpen() 回调函数来解决这个问题,因为在调用此函数时我们没有“MyDropdown__option--is-selected”class。

我的解决方法如下;

//when dropdown is not manually clicked then it does not scroll into view
onMenuOpen = () => {
  setTimeout(()=>{
    const selectedEl = document.getElementsByClassName("MyDropdown__option--is-selected")[0];
    if(selectedEl){
      selectedEl.scrollIntoView({behavior:'smooth', block:'nearest', inline: 'start'});
    }
  },15);
};

render(){
const {defaultOption, options} = this.props;

  return (
    <Select 
      options={options}
      value={defaultOption}
      onMenuOpen={this.onMenuOpen}
      onChange={(item: IDropdownOptions) => this.props.onSelect(item)}
      className ={"MyDropdown"}
      classNamePrefix={"MyDropdown"}
      isDisabled={this.props.isDisabled}
      isSearchable={this.props.isSearchable}
      >
    </Select>
  );
}