React - 如何在 react-select 中设置默认值 [英] React - How to set default value in react-select
问题描述
我在我的应用程序中使用了 react-select 来显示选择框.下面是我选择的代码.
I used react-select in my application for showing select box. below is code of my select.
<Select
className="custom-form-control mb-2"
name="organization_options"
options={this.organizationOptions()}
placeholder={false}
onChange={this.handleChange.bind(this)}
value={selectedValue === "" ? this.organizationOptions()[0] : selectedValue}
/>
以下是我在选择框中已有的选项
Below are the options i already have in select box
0: {value: "62", label: "Dfdf"}
1: {value: "128", label: "Dfdfdsf"}
2: {value: "151", label: "Fgfdgdfh"}
3: {value: "121", label: "Hhhfas"}
4: {value: "55", label: "My Sensor_56"}
5: {value: "13", label: "New Org"}
6: {value: "44", label: "Org 2"}
7: {value: "148", label: "Testing App"}
我有来自查询字符串的值,如 value="55",如果该值存在,我想在选择框中显示所选值.
I have the value from query string like value="55", if the value is present i want to show that selected value in select box .
我尝试了两种不同的方式,如下所示,
I tried in 2 different ways which are shown as below code ,
1)
selectedValue='55'
defaultValue={this.organizationOptions().find(op => {
return op.value === selectedValue
})}
2
defaultValue={{value: "55", label: "My Sensor_56"}}
但没有人工作,有人能告诉我如何设置 defaultV如果我没有选择值,是否已经有或不显示默认值?
But no one works, Can somebody tell me How can i set defaultV alue if already have or don't show default value if i don't have selected value ?
推荐答案
这里是我们在组织选项中找到的默认值,并将其作为值传递给 Select:
Here default value we are finding out in organization options and pass it as value in Select:
import React from 'react';
import Select from 'react-select';
export default class App extends React.Component {
organizationOptions = () => {
return [
{value: "62", label: "Dfdf"},
{value: "128", label: "Dfdfdsf"},
{value: "151", label: "Fgfdgdfh"},
{value: "121", label: "Hhhfas"},
{value: "55", label: "My Sensor_56"},
{value: "13", label: "New Org"},
{value: "44", label: "Org 2"},
{value: "148", label: "Testing App"}
]
}
render() {
const selectedValue = "55"
return (
<Select
value={this.organizationOptions().find(op => {
return op.value === selectedValue
})}
onChange={this.handleChange}
options={this.organizationOptions()}
/>
);
}
}
这篇关于React - 如何在 react-select 中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!