(React)动态下拉框示例。方法文档?

时间:2016-11-21 18:05:58

标签: javascript reactjs drop-down-menu

有人能指出我在任何动态React下拉框示例的方向吗?

我希望实现下拉功能,该功能将采用主要下拉选项的结果,以确定辅助下拉列表的输出。例如,从主要下拉列表中选择“伦敦”,将填充伦敦境内区域(行政区)的辅助下拉框。

我打算通过从firebasedb中选择数据来填充下拉框。

1 个答案:

答案 0 :(得分:3)

您可以创建选择框的选项列表,从您的道具或州动态做出反应。 运行下面的代码段,了解它的外观。

同时查看react's docs for more info on <select> elements中的反应。

&#13;
&#13;
class MyForm extends React.Component {
  constructor(props) {
    super(props)
    
    this.handleFirstLevelChange = this.handleFirstLevelChange.bind(this)
    this.handleSecondLevelChange = this.handleSecondLevelChange.bind(this)
    
    // Prepopulate with the first item for each level
    this.state = {
      firstLevel: Object.keys(props.options)[0],
      secondLevel: Object.keys(props.options)[0][0]
    }
  }
  
  handleFirstLevelChange(event) {
    this.setState({firstLevel: event.target.value});
  }
  
  handleSecondLevelChange(event) {
    this.setState({secondLevel: event.target.value});
  }
  
  render() {
    const renderOption = item => <option value={item}>{item}</option>

    const firstLevelOptions = Object.keys(this.props.options).map(renderOption)
    const secondLevelOptions = this.props.options[this.state.firstLevel].map(renderOption)
    
    return (
      <div>
        <p>
          <select onChange={this.handleFirstLevelChange} value={this.state.firstLevel}>
            {firstLevelOptions}
          </select>
        </p>
        <p>
          <select onChange={this.handleSecondLevelChange} value={this.state.secondLevel}>
            {secondLevelOptions}
          </select>
        </p>
      </div>
    )
  }
}

const options = {
  "USA": ["New York", "San Francisco"],
  "Germany": ["Berlin", "Munich"]
}

ReactDOM.render(
  <MyForm options={options} />,
  document.getElementById('app')
)
&#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='app'></div>
&#13;
&#13;
&#13;