在反应选择下拉菜单中设置默认值

时间:2019-08-04 22:04:32

标签: reactjs react-redux

我正在尝试在我的select标记中设置一个默认值,以便在每个onChange事件上都可以调用我的API。

我在线搜索了如何为select标签设置默认值,人们建议使用对我不起作用的defaultValue属性。

options.Request.RequestUri.ParseQueryString();
    let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
        return <option key={key} value={location.SERVICE_PROVIDER_LOCATION_ID}>{location.DESCRIPTION}</option>
    });

我希望看到一个“选择”值作为默认值,而其他则是我从API获得的值,但是我看不到“选择”值

3 个答案:

答案 0 :(得分:0)

尝试使用defaultValue参数。

 <Select
  name="form-dept-select"
  options={depts}
  defaultValue={{ label: "Select Dept", value: 0 }}
  onChange={e => {
              this.setState({
              department: e.label,
              deptId: e.value
              });
           }}
/>

答案 1 :(得分:0)

要默认查看Select,您需要在原始option之前添加一个option

<select
  value={this.state.selectedValue} //Add the selected value here, may be from state. For example `this.state.selectedValue` you can change the name whatever you have
  name="serviceProviderLocationDropDown"
  onChange={this.updateServiceProviderLocationId}
>
  <option>Select</option>   //By default selected
  {serviceProviderLocationNames}
</select>
您选择的

onChange具有updateServiceProviderLocationId功能,并且您可以在state中设置选定的值,您需要在上面的value道具中写下该值,以便成为controlled组件。

Demo

答案 2 :(得分:0)

我认为您需要在此处整理 html元素基础知识。因此,默认情况下要在下拉菜单中选择值,您需要将选择的内容添加到 html标签中,并且应该处理默认的选择项。

因此,您需要添加登录名以选择选项中的元素,并且在更改时,您应该能够获取默认值

let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
  return <option 
    key={key} 
    value={location.SERVICE_PROVIDER_LOCATION_ID} 
    selected={key=== PUT_INDEX_TO_BE_DEFAULT_SELECTED}
  >
    {location.DESCRIPTION}
  </option>
});