【问题标题】:How handle multiple select form in ReactJS如何在 ReactJS 中处理多选表单
【发布时间】:2018-10-09 22:45:16
【问题描述】:

我尝试在 ReactJS 中处理一个多表单选择选项。我试图启发 javascript 经典代码来处理这个问题,但我失败了。

我的代码只是不向我发送选择的值。怎么处理?

这是我的代码:

  class ChooseYourCharacter extends React.Component {

      constructor(props) {
        super(props);
        this.state = {value: 'coconut'};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

      handleChange(event) {
        this.setState({value: event.option});
      }

      handleSubmit(event) {
        alert('Your favorite flavor is: ' + this.state.value);
        event.preventDefault();
      }

      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <label>
              Pick your favorite La Croix flavor:
              <select multiple={true} value={this.state.value} onChange={this.handleChange}>
                <option value="grapefruit">Grapefruit</option>
                <option value="lime">Lime</option>
                <option value="coconut">Coconut</option>
                <option value="mango">Mango</option>
              </select>
            </label>
            <input type="submit" value="Submit" />
          </form>
        );
      }
    }
    ReactDOM.render(
             <ChooseYourCharacter/>,
             document.getElementById('root')
    )

【问题讨论】:

  • 如果您找到了自己问题的答案,您可以将其放在“答案”中并接受它,以用于记录目的
  • 好的,谢谢大家,我会把它放在常规延迟的末尾
  • 感谢 Holly Springsteen 将链接发送给我。我已经看过了,但另一种观点启发了我。

标签: javascript forms reactjs select


【解决方案1】:

我在这里使用 react bootstrap 4

   <Form.Group >
          <Form.Label>Form Label</Form.Label>
          <Form.Control
            as="select"
            multiple
            // value={formCatState}
            onChange={(event) => {
              let target = event.target as HTMLSelectElement
              console.log(target.selectedOptions);
            }}
          >
            <option>example cat 1</option>
            <option>Example cat 2</option>
            <option>Example cat 3</option>
            <option>Example cat 4</option>
          </Form.Control>
            <Form.Text muted> hold ctrl or command for multiple select</Form.Text>
        </Form.Group>

【讨论】:

    【解决方案2】:

    这里是如何使用功能组件和 useState 挂钩而不是类组件来获取用户选择的选项:

    import React, { useState } from "react";
    
    const ChooseYourCharacter = function(props) {
        const [selectedFlavors, setSelectedFlavors] = useState([]);
    
        const handleSelect = function(selectedItems) {
            const flavors = [];
            for (let i=0; i<selectedItems.length; i++) {
                flavors.push(selectedItems[i].value);
            }
            setSelectedFlavors(flavors);
        }
    
        return (
            <form>
                <select multiple={true} value={selectedFlavors} onChange={(e)=> {handleSelect(e.target.selectedOptions)}}>
                    <option value="grapefruit">Grapefruit</option>
                    <option value="lime">Lime</option>
                    <option value="coconut">Coconut</option>
                    <option value="mango">Mango</option>
                </select>
            </form>
        );
    };
    
    export default ChooseYourCharacter;
    

    【讨论】:

      【解决方案3】:

      根据我的基本理解,当您尝试在 reactJS 中处理 选择表单元素 时,您会在 HTMLOptionsCollection 中生成一个对象。

      此对象方法和属性的基本根是e.target.options

      您的项目存储在 e.target.options.value 属性中。

      要访问存储在 options.value 对象中的值,您可以使用 [i] 循环值,即 e.target.options[i].value 属性。

      e.target.options[i].value 返回字符串数据类型。

      按照我刚才所说的,我假设对象的存储遵循以下数字增加约定:

      e.target.options[i].value where { [i] : value, [i +1] : value (...)}...

      通过使用 e.target.options[i].selected 您可以控制是否有值存储在特定位置。

      e.target.options[i].selected 返回一个布尔值,对处理代码流很有用。

      现在由你决定。


      这是我在 JSX 中使用 javascript 代码处理多个选择表单的代码:

      // Create the React Component
      
      
          class ChooseYourCharacter extends React.Component {
      
                // Set the constructor
                constructor(props) {
                  super(props);
                  this.state = {value: 'coconut'};
      
                  // bind the functions
                  this.handleChange = this.handleChange.bind(this);
                  this.handleSubmit = this.handleSubmit.bind(this);
                }
      
                // extract the value to fluently setState the DOM
                handleChange (e) {
                  var options = e.target.options;
                  var value = [];
                  for (var i = 0, l = options.length; i < l; i++) {
                    if (options[i].selected) {
                      value.push(options[i].value);
                    }
                  }
                  this.setState({value: value});
                }
      
                // display in client-side the values choosen
                handleSubmit() {
                   alert("you have choose :" + this.state.value);
      
               }
      
      
          (...)
      

      【讨论】:

      • 我不明白这将如何工作。每次选择选项时都会调用handleChange,并覆盖value 的先前值。我刚刚试了一下,可以看到我所说的正在发生的事情。
      【解决方案4】:

      当你使用多选时,你应该将你的状态变量声明为一个数组

        constructor(props) {
          super(props);
          this.state = {value: []};//This should be an array
      
          this.handleChange = this.handleChange.bind(this);
          this.handleSubmit = this.handleSubmit.bind(this);
        }
      

      我为带有多选控件的 reactjs 表单发布创建了一个博客。你可以去这里了解更多详情https://handyopinion.com/git-commands-cheat-sheet/

      【讨论】:

        【解决方案5】:

        目前正在学习 React,我在 reactjs.org site 上注意到了相同的代码。以下是我处理多个选定选项的解决方案。

        1. 在构造函数中,使用数组作为状态中'value'的初始值
        2. 在handleChange方法中,使用Array.from()将事件目标的selectedOptions(HTMLOptionsCollection - 类数组)转换为数组,并使用映射函数从每个item中获取值

        class ChooseYourCharacter extends React.Component {
        
              constructor(props) {
                super(props);
                //this.state = {value: 'coconut'};
                this.state = {value: ['coconut']};
        
                this.handleChange = this.handleChange.bind(this);
                this.handleSubmit = this.handleSubmit.bind(this);
              }
        
              handleChange(event) {
                //this.setState({value: event.option});
                this.setState({value: Array.from(event.target.selectedOptions, (item) => item.value)});
              }
        
              handleSubmit(event) {
                alert('Your favorite flavor is: ' + this.state.value);
                event.preventDefault();
              }
        
              render() {
                return (
                  <form onSubmit={this.handleSubmit}>
                    <label>
                      Pick your favorite La Croix flavor:
                      <select multiple={true} value={this.state.value} onChange={this.handleChange}>
                        <option value="grapefruit">Grapefruit</option>
                        <option value="lime">Lime</option>
                        <option value="coconut">Coconut</option>
                        <option value="mango">Mango</option>
                      </select>
                    </label>
                    <input type="submit" value="Submit" />
                  </form>
                );
              }
            }
            ReactDOM.render(
                     <ChooseYourCharacter/>,
                     document.getElementById('root')
            )
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
        <div id="root"></div>

        【讨论】:

          猜你喜欢
          • 2010-12-19
          • 1970-01-01
          • 2014-01-03
          • 1970-01-01
          • 2018-06-09
          • 2020-05-16
          • 2020-11-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多