使用多下拉菜单时获取反应选择选项 [英] Get react-select selected option when using multi dropdown
问题描述
我的页面上有两个可用的 react-select 下拉菜单,其中一个允许用户选择 A 或 B,并且允许他们从蓝色、黄色、红色"中选择多个项目.
I have two working react-select drop downs on my page, one that allows the user to select A or B, and one that allows them to choose multiple items from "blue, yellow , red".
当他们选择了这些项目时,我想使用它们.现在我只想检查已选择的值,所以我只是将它们打印到屏幕上.对于单选下拉菜单,我成功地使用了 github 中的示例代码.如下:
When they have chosen these items, I want to use them. For now I just want to check the values that have been selected, so I'm just printing them to screen. For the single selection drop down I have used the example code from the github successfully. This is as follows:
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
/>
);
}
}
我的问题是如何为多选项成功执行此操作?用户可以选择任意数量的选项,但在打印已选择的选项时会抛出未定义"错误.我认为这是因为该选项存储在一个数组中,但我不确定.
My question is how do I successfully do this for the multi option? The user can select as many as they wish, but an 'undefined' error is thrown when it prints the option that has been selected. I think this is because the option is stored in an array but I'm not sure.
谢谢大家.
推荐答案
你需要改变handleChange
来处理isMulti
.举个例子:
You need to change the handleChange
to deal with the isMulti
. Here's an example:
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
这篇关于使用多下拉菜单时获取反应选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!