使用多下拉菜单时获取react选择选项

IT技术 javascript reactjs react-select
2021-05-09 15:45:50

我的页面上有两个可用的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
      />
    );
  }
}

我的问题是如何为多选项成功执行此操作?用户可以选择任意数量的选项,但在打印已选择的选项时会抛出“未定义”错误。我认为这是因为该选项存储在一个数组中,但我不确定。

谢谢大家。

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 { selectedOptions } = this.state;

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

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

这是一个工作示例:https : //stackblitz.com/edit/react-czf4ib

如果您使用的是 React 钩子,这里是您如何从react-selectwithisMultiprops中获取选定值的方法

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

希望能帮助到你!

对于数组中的存储值,试试这个 [ "purple", "red", "blue" ]

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

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

onChange={this.handleChange}