React - How to Populate two Dropdowns based on selection in another

后端 未结 1 1696
不思量自难忘°
不思量自难忘° 2021-01-15 06:54

I need to change the contents of dropdown Method&Minorhead based on the selection in dropdown MajorHead using React.

If I select cheating in majorhead, then it\'

相关标签:
1条回答
  • For each option in your major head Select, i would create an array of supported values for method and minor.

    class App extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          selectedView: 'Cheating'
        }
      }
      
      render() {
        const { selectedView } = this.state
        const VIEWS = [
          {
            name: 'Cheating', 
            minor: ['a', 'b'], 
            method: ['apple', 'orange']
          }, {
            name: 'Abductions', 
            minor: ['AB', 'BC', 'X'], 
            method: ['cat', 'dog']
          }
        ]
    
        const getMajorMethod = () => {
          const view = VIEWS.filter(({name}) => name === selectedView)[0]
          return (
            <div>
              <select>
                {view.minor.map(m => <option>{m}</option>)}
              </select>
              <select>
                {view.method.map(m => <option>{m}</option>)}
              </select>
            </div>
          )
        }
        return (
          <div>
            <select onChange={(e) => this.setState({selectedView: e.target.value})}>
              {VIEWS.map(({name}) => <option value={name}>{name}</option>)}
            </select>
    
            {getMajorMethod()}
          </div>
        )
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('app'))
    <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>

    A structure like this will allow you to (within your initial MAJOR select) map over your VIEWS and apply the name prop to the options.

    You can then have another map that shows two other selects (minor & method) with the VIEWS relative minor and method arrays being their options

    0 讨论(0)
提交回复
热议问题