多项选择无效,仅提供最后点击的值

我从react-bootstrap documentation实现了一个多选下拉菜单。

它不允许我进行多项选择,而只能获得最后单击的选项。我将状态变量设置为数组。我还想念什么?应用是使用create-react-app创建的。

我在类构造函数中将状态设置为数组。事件处理程序的绑定也可以在构造函数中完成。

接下来,我将显示事件处理程序,然后显示带有onChange并将其值设置为state的表单组。 (请注意,我有一个下拉菜单可以正常工作。)

然后我将此值传递给几个类,然后将其解析为JSON。最后的粘贴是这些类。我删除了其他参数,以便于阅读,任何想法,随时询问更多信息。

this.state = {

 codeCoverage: [],}

 this.handleCodeCoverageChange = this.handleCodeCoverageChange.bind(this);
//Event handlers below
    handleCodeCoverageChange(event){
        this.setState({
            codeCoverage: event.target.value
        })
    }
<Form.Group>
<Form.Label>Please choose your desired code coverage software(s)</Form.Label>
<Form.Control as="select" value={this.state.codeCoverage} onChange={this.handleCodeCoverageChange} multiple>
<option value="">--Please choose an option--</option>
<option value="cobertura">Cobertura</option>
<option value="sonarcube">Sonarcube</option>
</Form.Control>
</Form.Group>
var configurator = new Configurator(this.state.codeCoverage)
class Configurator
{
    constructor(
        code_coverage)
    {
        this.pipeline = new Pipeline(code_coverage)
    }

}
class Pipeline
{
    constructor(code_coverage)
    {
        this.analysisAndSecurity = new AnalysisAndSecurity(code_coverage)
    }
class AnalysisAndSecurity{
 parameter
    constructor(code_coverage)
    {
        this.code_coverage = code_coverage

    }
}
xiaoxiamiit 回答:多项选择无效,仅提供最后点击的值

在handleChange函数中,将state.codeCoverage的选定值而不是adding分配给选定元素的数组。这就是为什么当您选择另一个元素时,它会删除旧值。我建议记录e.target.valuethis.state.codeCoverage以便更好地理解。至于解决方法:

由于您使用的是multiple select,因此期望将数组作为值而不是单个值。因此,您需要在handleChange方法中更改两件事。

  1. 首先,您需要将元素add设置为现有值,而不要替换它们。
  2. 您需要处理再次单击选定元素并使其变为未选中状态的情况。

您可以执行以下两个任务:

handleChange = e => {
  const { codeCoverage } = this.state;

  // Find the value selected the codeCoverage array
  const index = codeCoverage.indexOf(e.target.value);

  // If the value is not found then add it to the array
  if (index === -1) codeCoverage.push(e.target.value);
  // If value found then remove the value to unselect
  else codeCoverage.splice(index,1);

  // Set the state so that the component reloads with the new value
  this.setState({ codeCoverage: [...codeCoverage] });
};
本文链接:https://www.f2er.com/3158369.html

大家都在问