代码之家  ›  专栏  ›  技术社区  ›  Vishal

React-如何在React select中设置默认值

  •  1
  • Vishal  · 技术社区  · 6 年前

    react-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}
    />
    

    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”,如果有值,我想在选择框中显示所选的值。

    1)

    selectedValue='55'
    defaultValue={this.organizationOptions().find(op => {
       return op.value === selectedValue
    })}
    

    2

    defaultValue={{value: "55", label: "My Sensor_56"}}
    

    值(如果已经有)或不显示默认值(如果我没有选定值)?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Pardeep Dhingra    6 年前

    这里是我们在组织选项中找到的默认值,并将其作为选择中的值传递:

    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()}
          />
        );
      }
    }