简体   繁体   中英

How can I convert a standard 'select' tag into react-select

Im want to turn this into a from react-select. All the data being passed through works perfectly with but when I change it to it doesn't work (because it requires other options), I was wondering how to make this piece of code compatible with React-Select.

<div>
   <select value={this.state.currency} onChange={this.getTest}>
      {this.state.items.map((obj, index) => 
         <option key={${index}-${obj.country}} value={obj}> {obj} </option>
      )} 
   </select>
</div>

There is no need to specify "value" to your select element. Rather you need to set your state accordingly on onChange function.

If this was done to somehow "bind" the select option and the state, you're probably not going the react way (probably due to Angular background where such two way bindings is the way to go).

Good example from library

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
];

class App extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  }
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

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