【问题标题】:React-select scrollintoView does not scroll the selected valuereact-select scrollintoView 不滚动选中的值
【发布时间】:2021-06-16 03:38:47
【问题描述】:

我正在使用 react-select3.2.0。当我打开我的选择框并选择一个选项时。然后我再次打开我的选择下拉菜单,然后选择的值就会出现。 但是当下拉列表的值来自道具而不是通过打开下拉列表手动选择时,问题就来了。然后,当我打开下拉菜单时,它不会滚动查看所选值。 我也尝试过 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>

【问题讨论】:

    标签: reactjs typescript react-select


    【解决方案1】:

    通过查找选定的索引来赋予 value 属性

    <Select options={options} value={options[selectedIndex]} />
    

    【讨论】:

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

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

    我的解决方法如下;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2017-07-15
      • 2023-01-03
      • 2013-06-21
      • 2019-03-17
      • 2020-10-24
      • 2014-08-31
      相关资源
      最近更新 更多