简体   繁体   中英

React-select does not show the selected value in the field

i have a react-select component which i define like this:

<Select
            id="portf"
            options={opts}
            onChange={value => portfolioSelector(value)}
            placeholder="Select Portfolio"
          />

with opts = [{label: any, value:1}, {label:Two, value:2}] .

The values when selected are stored in the state via portfolioSelector function. The problem is that when i select a value it wasn't show in the select field. My main component is this:

const PortfolioSelector = ({
  opts,
  portfolioSelector
}) => {
  if (opts) {
    return (
      <div className="portfolio select-box">
        <label htmlFor="selectBox" className="select-box__label">
        Portfolio
        </label>
        <div className="select-box__container">
          <Select
            id="portf"
            options={opts}
            onChange={value => portfolioSelector(value)}
            placeholder="Select Portfolio"
          />
        </div>
        <div className="separator" />
      </div>
    );
  }
  return (
    <div>Loading</div>
  );
};

Do you know why?

This is an alternative solution that i used.

Demo: https://codesandbox.io/s/github/mkaya95/React-Select_Set_Value_Example

import React, { useState } from "react";
import Select from "react-select";

export default function App() {
  const [selectedOption, setSelectedOption] = useState("none");
  const options = [
    { value: "none", label: "Empty" },
    { value: "left", label: "Open Left" },
    { value: "right", label: "Open Right" },
    {
      value: "tilt,left",
      label: "Tilf and Open Left"
    },
    {
      value: "tilt,right",
      label: "Tilf and Open Right"
    }
  ];
  const handleTypeSelect = e => {
    setSelectedOption(e.value);
  };

  return (
    <div>
      <Select
        options={options}
        onChange={handleTypeSelect}
        value={options.filter(function(option) {
          return option.value === selectedOption;
        })}
        label="Single select"
      />
    </div>
  );
}

First thing is you are created the wrong array, if label: any or Two is string you have to add double quote. Look at this:

opts = [{label: "any", value:1}, {label:"Two", value:2}]

Second, You must remember the options in this case is opts is an array of object which have label and value, what the data you want to add to your state?

      <Select
        id="portf"
        options={opts}
        onChange={value => portfolioSelector(value.value /* or if you want to add label*/ value.label)}
        placeholder="Select Portfolio"
      />
<Select
options={this.props.locale}
onChange={this.selectCountryCode}
value={{label : this.state.selectedCountryLabel}}
/>

The value property expects the shape Array.

I fixed it. You forgot add value property. Use this, check the working code:

const opts = [{ label: 'any', value: 1 }, { label: 'Two', value: 2 }];

const PortfolioSelector = ({ options }) => {
  if (options) {
    return (
      <div className="portfolio select-box">
        <label htmlFor="selectBox" className="select-box__label">
          Portfolio
        </label>
        <div className="select-box__container">
          <Select
            id="portf"
            options={options}
            value={this.state.opts1}
            onChange={value => this.setState({ opts1: value })}
            placeholder="Select Portfolio" />
        </div>
        <div className="separator" />
      </div>
    );
  }
  return <div>Loading</div>;
};

and call your component

<PortfolioSelector options={opts} />

this is my solution

Demo: https://codesandbox.io/s/prod-rgb-o5svh?file=/src/App.js

code:

 import axios from 'axios' import {useEffect, useState} from 'react' import Select from 'react-select' import "./styles.css"; export default function App() { const [users, setUsers] = useState() const [userId, setUserId] = useState() useEffect(()=>{ const getUsers = async () => { const {data} = await axios.get('https://jsonplaceholder.typicode.com/users') setUsers(data) } getUsers() },[]) const options = users && users.map(user =>{ return {label: user.name, value: user.id} }) console.log(userId) return ( <div className="App"> {users && ( <Select placeholder='Select user...' isSearchable value={options.label} options={options} onChange={(option) => setUserId(option.value) } /> )} </div> ) }

您可以简单地将 value 属性设置为Selected.label

value={selectedOption.label}

The value is handled really bad, and it needs hacks like here , explained here .

Long story short; the value works differently. You'd expect

value={MY_VALUE} , but it works instead

value={{label: MY_VALUE}} .

opts = [{label: any, value:1}, {label:Two, value:2}]

值必须是字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM