根据反应中另一个选择框的值动态加载选择框的选项

2023-11-29

我正在尝试创建 2 个选择框,其中第一个选择框的选项是固定的,但第二个选择框的选项根据第一个 div 的选定值而变化。

例如: 第一个选择:

<select>
    <option>Integers</option>
    <option>Alphabets</option>
</select>

然后,如果在第一个选择中选择“整数”,那么我希望在第二个选择框中选择整数 1 到 10 作为选项。但如果选择字母,a 到 z 应该出现在第二个选择框的选项中。


您可以创建一个查找表对象,其中包含整数和字母,每个对象都有一个相关的键。
然后在一个select您用所选更新状态key而在另一个select您渲染与所选相对应的选项key.


Here is a running example:

const lookup = {
  "int": [
    { id: '1', text: '1' },
    { id: '2', text: '2' },
    { id: '3', text: '3' },
    { id: '4', text: '4' },
    { id: '5', text: '5' }
  ],
  "abc": [
    { id: 'a', text: 'a' },
    { id: 'b', text: 'b' },
    { id: 'c', text: 'c' },
    { id: 'd', text: 'd' },
    { id: 'e', text: 'e' }
  ]
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataValue: 'int'
    }
  }

  onChange = ({ target: { value } }) => {
    this.setState({ dataValue: value });
  }

  render() {
    const { dataValue } = this.state;
    const options = lookup[dataValue];
    return (
      <div>
        <select onChange={this.onChange}>
          <option value="int">Integers</option>
          <option value="abc">Alphabets</option>
        </select>
        <hr />
        <select>
          {options.map(o => <option key={o.id} value={o.id}>{o.text}</option>)}
        </select>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据反应中另一个选择框的值动态加载选择框的选项 的相关文章

随机推荐