【问题标题】:ReactJs How to handle event handler only after multiple selection of dropdown?ReactJs如何仅在多选下拉列表后处理事件处理程序?
【发布时间】:2018-02-20 18:42:03
【问题描述】:

我有以下带有多选下拉列表的代码。句柄更改调用从下拉列表中选择每个值。我怎样才能改变它以仅在选择多个值后才调用 handleChange 函数?

handleChange(e) {
    console.log(e.target.value);
}

render() {

    return(
        <select className="form-control" key="1" name="degree" onChange={this.handleChange} multiple>
            <option value="1" key="1">1</option>
            <option value="2" key="2">2</option>
            <option value="3" key="3">3</option>
            <option value="4" key="4">4</option>
            <option value="5" key="5">5</option>
        </select>
        )
}

更新: 我需要在控制台中获取所选值的数组是我的基本要求。

【问题讨论】:

  • 您如何知道何时选择了所需的值,以及列表中的任何其他值?
  • 我的意思是在选择多个值之后。那里有任何事件处理程序可以这样做吗?
  • 下拉列表中的“选择多个值”是什么意思?
  • 所以条件是selectedValues &gt; 1?
  • 我相信你在找 -> e.target.selectedOptions 不是一个值

标签: javascript reactjs


【解决方案1】:

您总是可以在您的操作处理程序中使用快速失败

handleChange(e) {
    const requiredValues = [3, 5]
    if (!requiredValues.includes(e.target.value) return
    ...
}

【讨论】:

  • 我就是这样做的!
【解决方案2】:

下划线提供了一个名为_.after() 的方法。这可能符合您的要求。

【讨论】:

    【解决方案3】:

    您可以在拥有多个值后执行“选择”处理程序逻辑。

    一个例子是将选定的值存储在 state 中,处理程序如下所示:

    onChangeHandler = (e) => {
      this.setState({ values } => {
        const newValues = values;
        const currentValue = e.target.value;
    
        const index = values.indexOf(currentValue);
    
        if (index > -1) {
          // Remove value
          newValues.splice(index, 1);
        } else {
          // Add value
          newValues.push(currentValue);
        }
    
        // You can do your logic here, before state is updated
        // if (newValues.length > 1) {
        // do multiple values logic
        // }
    
        // Update state
        return {
          values: newValues
        }
      }, () => {
        // You can do your logic here, after state is updated
        // if (this.state.values.length > 1) {
        // do multiple values logic
        // }
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2018-10-09
      • 1970-01-01
      • 2012-03-18
      相关资源
      最近更新 更多