[英]setting default-value in react select dropdown
I am trying to set a default value in my select tag so that on every onChange event I can call an API which is my requirement. 我试图在我的select标记中设置一个默认值,以便在每个onChange事件上都可以调用我的API。
I searched online on how to set defaultvalue for select tag, people suggested to use defaultValue attribute which did not work for me. 我在网上搜索了如何为选择标签设置默认值,人们建议使用对我不起作用的默认值属性。
let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
return <option key={key} value={location.SERVICE_PROVIDER_LOCATION_ID}>{location.DESCRIPTION}</option>
});
<select
defaultValue = {{ label: "Select", value: 0}}
name="serviceProviderLocationDropDown"
onChange={this.updateServiceProviderLocationId}
>
{serviceProviderLocationNames}
</select>
I expected to see a "select" value as default and others to be the values that I got from an API, but I couldn't see the "select" 我希望看到一个“选择”值作为默认值,而其他值则是从API获得的值,但是我看不到“选择”值
Try using the defaultValue
parameter. 尝试使用
defaultValue
参数。
<Select
name="form-dept-select"
options={depts}
defaultValue={{ label: "Select Dept", value: 0 }}
onChange={e => {
this.setState({
department: e.label,
deptId: e.value
});
}}
/>
To see Select
by default, you need to add an option
before your original option
as, 要查看默认情况下的
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
of your select you have updateServiceProviderLocationId
function, and you might set selected value in state
, you need to write that in value
prop above so that it will become a controlled
component. 您选择的
onChange
具有updateServiceProviderLocationId
函数,并且您可以将选定的值设置为state
,您需要将其写在上面的value
属性中,以便它将成为controlled
组件。
I think you need to brush up 我想你需要复习 html element basics here.
html元素基础。 So to select value in dropdown by default you need to add selected to
因此,默认情况下要在下拉菜单中选择值,您需要将selected添加到 html tag and that should take care of default selected item.
html标记,它应注意默认选择的项目。
So you need to add login to select the element in the option and while change you should be able to get default value 因此,您需要添加登录名以选择选项中的元素,并且在更改时,您应该能够获取默认值
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>
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.