reactjs - 下拉选择2个字段

时间:2018-03-29 16:11:51

标签: html css reactjs

我正在尝试使用2个字段对选择组件进行编码,类似于http://www.apartments.com。我已经研究过antd,bootstrap,semantic等,但没有看到类似的组件,所以我想知道是否有人知道一个包/库来完成这个。或者,最好将它编码为带有2个选项卡的下拉列表,每个选项卡作为输入字段?

enter image description here

1 个答案:

答案 0 :(得分:1)

不确定这是否是您要找的,但您可以构建自己的自定义选择组件,如下所示:



class Select extends React.Component {
  
  state = {
    activeMenu: 'min',
    open: true,
    min: '',
    max: ''
  };
  
  toggleMenu = e => {
    this.setState({
      activeMenu: e.target.name
    });
  };
  
  toggleOpen = () => {
    this.setState( prevState => {
      return { open: !prevState.open }
    });
  };
  
  getMenuOptions = () => {
    let options = [];
    switch(this.state.activeMenu){
      case 'min': {
        options = ['$1000','$2000','$3000','$4000','No Min'];
        break;
      }
      case 'max': {
        options = ['$1000','$2000','$3000','$4000','No Max'];
        break;
      }
    }
    return options.map( (option, i) => {
      return (
        <li key={i} onClick={this.handleSelect.bind(this, this.state.activeMenu, option)}>
          {option}
        </li>
      )
    });
  };
  
  handleSelect = (menu, value) => {
    this.setState({
      [menu]: value
    });
  };

  render() {
    const { open, min, max, activeMenu } = this.state;
    const menuOptions = this.getMenuOptions();
    return(
      <div className="select">
        <span onClick={this.toggleOpen} >Rent Range</span>
        {open && (
          <div>
            <div>
              <input type="text" name="min" value={min} onFocus={this.toggleMenu} autoFocus />
              -
              <input type="text" name="max" value={max} onFocus={this.toggleMenu} />
            </div>
            <div>
              <ul className={activeMenu}>
                {menuOptions}
              </ul>
            </div>
          </div>
        )}
      </div>
    )
  }
}

ReactDOM.render(<Select/>,document.getElementById('root'));
&#13;
span {
  display: block;
  cursor: pointer;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 5px;
}
li:hover {
  cursor: pointer;
}
ul.max {
  float: right;
}
.select {
  width: 300px;
  border: 1px solid #222;
  overflow: hidden;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;