React-Select 如何保持菜单 open/close 的默认行为并在单击按钮时添加到打开菜单?

React-Select how to keep default behavior of menu open/close plus add to open menu on button click?

我有一个 react-select 组件可以在 api 上执行搜索,还有一个按钮可以开始搜索。

我尝试在单击按钮后设置 menuIsOpen={true} 但这破坏了原始的焦点模糊行为菜单不再关闭模糊。 试图在没有打开菜单的输入上设置 .focus()。

当前的原始行为菜单在聚焦时打开,在模糊时关闭,我想保留这个加上我想在单击按钮后打开菜单。

要实现您想要的效果,您需要使用受控的 menuIsOpen 道具。

我认为保留 react-select 所有本机功能的最简单方法是使用道具 onInputChangeonFocus 的组合,如下面的代码:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      menuIsOpen: false
    };
  }

  onInputChange = (options, { action }) => {
    if (action === "menu-close") {
      this.setState({ menuIsOpen: false });
    }
  };

  openMenu = () => {
    this.refs.focus();
    this.setState({ menuIsOpen: true });
  };

  render() {
    return (
      <div className="App">
        <Select
          ref={r => {
            this.refs = r;
          }}
          options={options}
          onFocus={this.openMenu}
          onInputChange={this.onInputChange}
          menuIsOpen={this.state.menuIsOpen}
        />

        <button onClick={this.openMenu}>Open Select</button>
      </div>
    );
  }
}

这里是live example.

我在 React 中使用这个功能,只打开一个选项卡,所以当你打开另一个选项卡时,上一个选项卡将关闭。

const openSingleTab = (id) => {
    const newData1 = data.map((item) => {
        if(item.id === id){
          return {...item, isOpened: !item.isOpened}
        }
        return {...item, isOpened: false}
      })

    setData(newData1)
  }

如果你想保持聚焦行为,你应该这样做 在构造函数中添加一个引用

    constructor(props) {
        super(props);
        this.state = { open: false }
        this.selectRef = React.createRef();
    }

然后添加这个关闭方法

close() {
        this.setState({ open: false });
        this.selectRef.current.blur();
    }

和 select 组件

<Select
    closeMenuOnSelect={props.closeMenuOnSelect || true}
    openMenuOnClick={() => this.setState({ open: true })}
    onFocus={() => this.setState({ open: true })}
    onBlur={() => this.setState({ open: false })}
    menuIsOpen={this.state.open}
    onInputChange={() => {
        if (props.closeMenuOnSelect) {
        this.close();
    }
    }}
    ref={this.selectRef}
    >
</Select>