使用多重下拉菜单时获取反应选择所选选项

时间:2018-11-07 14:45:07

标签: javascript reactjs react-select

我在页面上有两个有效的react-select下拉菜单,一个允许用户选择A或B,另一个允许他们从“蓝色,黄色,红色”中选择多个项目。

当他们选择这些项目时,我想使用它们。现在,我只想检查已选择的值,所以我只是将它们打印到屏幕上。对于单选下拉列表,我成功地使用了来自github的示例代码。如下所示:

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

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    document.write(`Option selected:`, selectedOption.value); //this prints the selected option
  }
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
        //isMulti //added when the user can pick more than one
      />
    );
  }
}

我的问题是,如何针对multi选项成功做到这一点?用户可以根据需要选择任意数量,但是在打印已选择的选项时会引发“未定义”错误。我认为这是因为该选项存储在数组中,但是我不确定。

谢谢。

3 个答案:

答案 0 :(得分:3)

您需要更改handleChange才能处理isMulti。这是一个示例:

import React, { Component } from 'react';
import { render } from 'react-dom';
import Select from 'react-select';

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

class App extends React.Component {
  state = {
    selectedOptions: [],
  }

  handleChange = (selectedOptions) => {
    this.setState({ selectedOptions });
  }

  render() {
    const { selectedOption } = this.state;

    return (
      <React.Fragment>
        <Select
          isMulti
          value={selectedOption}
          onChange={this.handleChange}
          options={options}
        />
      {this.state.selectedOptions.map(o => <p>{o.value}</p>)}
      </React.Fragment>
    );
  }
}

render(<App />, document.getElementById('root'));

这是一个有效的示例:https://stackblitz.com/edit/react-czf4ib

答案 1 :(得分:2)

如果您使用的是React钩子,则可以使用react-select属性从isMulti获取选定的值。

import React, {useState} from 'react';
import Select from 'react-select';
import { useForm } from 'react-hook-form';
import { handleSubmit } = useForm();

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

const FormComponent = (props) => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  const handleChange = (options) => {
    setSelectedOptions(options);
  };

  const onSubmit = (formData, event) => {
     console.log("Form Data: ", formData)
     console.log("Selected Options: ", selectedOptions)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Select
          isMulti = {true}
          options={options}
          closeMenuOnSelect={false}
          onChange={handleChange}/>

     <button type="submit">Save</button>
    </form>
  );
}

希望有帮助!

答案 2 :(得分:0)

对于数组中的存储值,请尝试此操作 [“紫色”,“红色”,“蓝色”]

 handleChange = (selectedOptions) => {
    let catArray = [];
    selectedOptions.map(o => 
       catArray.push(o.value)
   );

   this.setState({selectedOptions:catArray});
}

onChange = {this.handleChange}