0

在我的反应应用程序中,我有一个返回用户详细信息的端点和另一个返回国家/地区的端点,我在 中调用它们componentDidMount,我有一个国家/地区下拉列表,它的默认值/选项应该是从用户详细信息端点返回的国家/地区它的选项应该是从国家端点返回的国家列表,问题是当我使用 value 属性为选择设置默认值时,它始终为 null 并且不显示值,所以我尝试使用<option selected="selected">{this.state.country}</option>但onChange 函数在我使用它时不起作用,那么实现它的最佳方法是什么,这里是代码:

使用值属性:

<select value={this.state.country} onChange={this.handleChange}>{this.renderCountries()}</select>

使用选定的选项:

<select onChange={this.handleChange}>
  <option selected="selected">{this.state.country}</option>
    {this.renderCountries()}
</select>

OnChange 函数:

handleChange = event => { 
    this.setState({ selectedOption: event.target.value });
};

渲染选项:

 renderCountries() {
   return this.state.countries.map(country => (
     <option key={country.id} value={country.id}>
       {country.name}
     </option>
    ));
 }
4

1 回答 1

0

设置this.state.country为从端点返回的值。

<select value={this.state.country} onChange={this.handleChange}> . 
    {this.renderCountries()}
</select>

handleChange需要 setState为countrynot 。selectedOption这是因为valueselect 上的属性是this.state.country

  handleChange = event => {
    this.setState({ country: event.target.value });
  };

  renderCountries = () => {
    return this.state.countries.map(country => (
      <option key={country.id} value={country.id}>
        {country.name}
      </option>
    ));
  };

希望这可以解决您的问题。

于 2020-01-13T15:35:31.163 回答