首页 > 解决方案 > 反应选择显示和隐藏菜单列表

问题描述

我正在尝试使用反应选择。我有一定的条件(布尔值),当参数为 时true,react-select 的某些属性/属性会根据逻辑而改变。一个如果他们是menuList。我的目标,如果参数是true,我想要menuList显示和搜索,但是当 时false,我想要menuList隐藏但仍然可用(未禁用,这就是我使用onChange和支持的原因onInputChange)。这是我到目前为止设置的内容:

const isExist = true;
    return (
      <div style={{ width: '50%', margin: 20 }}>
        <Select
          id="asd"
          value={selectedOption}
          onChange={isExist ? this.handleChange : null}
          onInputChange={isExist ? null : e => this.tests(e) }
          options={options}
          isClearable={true}
          styles={style}
          placeholder="Please type"
          noOptionsMessage={() => isExist ? 'Zero Result' : null}
          components={{ MenuList: () => isExist ? 'display the menu but how?' : null }}
        />
      </div>
    );

任何帮助都会有所帮助。谢谢!

标签: reactjsselectreact-select

解决方案


根据您描述的行为,您可以使用这样的受控menuIsOpen道具:

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

    this.state = {
      isExist: false,
      menuIsOpen: false,
      selectedOption: null
    };
  }

  onChange = e => {
    this.setState({
      selectedOption: e
    });
  };

  onInputChange = (options, { action }) => {
    if (this.state.isExist) {
      if (action === "menu-close") {
        this.setState({ menuIsOpen: false });
      }
    } else {
      if (action === "input-change") {
        // do whatever you want with the entered value
      }
    }
  };

  onFocus = e => {
    if (this.state.isExist) this.setState({ menuIsOpen: true });
  };

  render() {
    return (
      <div style={{ width: "50%", margin: 20 }}>
        <Select
          id="asd"
          value={this.state.selectedOption}
          onFocus={this.onFocus}
          onChange={this.onChange}
          onInputChange={this.onInputChange}
          options={options}
          isClearable={true}
          placeholder="Please type"
          noOptionsMessage={() => (this.state.isExist ? "Zero Result" : null)}
          menuIsOpen={this.state.menuIsOpen}
        />
      </div>
    );
  }
}

这里有一个活生生的例子


推荐阅读