React JS-如何显示2个下拉列表并显示静态json中的数据

时间:2018-09-27 08:33:14

标签: json reactjs static dropdown

我是React JS的新手 我有2个下拉菜单:国家和城市。 我想借助静态json显示基于国家/地区的城市 有人可以帮助我吗?

 [
  {
    "id": "1",
    "country": "India",
    "cities": [
      {
        "id": "01",
        "cityName": "Delhi"
      },
      {
        "id": "02",
        "cityName": "Mumbai"
      },
      {
        "id": "03",
        "cityName": "Pune"
      }
    ]
  },
  {
    "id": "2",
    "country": "Canada",
    "cities": [
      {
        "id": "01",
        "cityName": "Toronto"
      },
      {
        "id": "02",
        "cityName": "Ottawa"
      },
      {
        "id": "03",
        "cityName": "Winnipeg"
      }
    ]
  }
]

import * as React from 'react'; import * as styles from './App.module.scss'; const App = () => { return ( <div className={styles.app}> <div> <span>Country: </span> <select> <option>Select Country</option> </select> </div> <div> <span>City: </span> <select> <option>Select Country</option> </select> </div> </div> ); }; export default App;

2 个答案:

答案 0 :(得分:0)

只需将Future国家/地区的方法设置为onchange,然后在该方法中按所选国家/地区过滤城市

dropdown

答案 1 :(得分:0)

尝试类似的方法,然后将数据作为道具传递。您应该根据需要进行重构,并使其更具通用性。

class SelectComponent extends Component {

  state = {country: 0, cityName: 0};

  clicked = () => { console.log("clicked") };

  handleChange = (key, ev) => {
    let newState = { [key]: parseInt(ev.target.value) };

    //reset city to 0 if country changes
    if(key !== "cityName") {
        newState.cityName = 0;
    }

    this.setState(newState);
  };

  render() {

    const { data } = this.props;

    const select = (title, data, fieldName) => {
        return (
            <div>
                <span>{title}:</span>
                <select onChange={(event) => this.handleChange(fieldName, event)}>
                    {data.map((value, key) =>
                      <option value={key}
                              selected={this.state[fieldName] === key}
                      >
                        {value[fieldName]}
                      </option>)
                    }
                </select>
            </div>);
  };

    return (
        <div className={styles.app}>
            {
                [select("Country", data, "country"), select("City", data[this.state.country].cities, "cityName")]
            }
        </div>
    );
  }
};

Live Preview