如何处理ReactJS

时间:2018-04-29 19:13:08

标签: javascript forms reactjs select

我尝试在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')
    )

5 个答案:

答案 0 :(得分:4)

这里是如何使用功能组件和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;

答案 1 :(得分:2)

在我的基本理解中,当您尝试在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 {{i]:value,[i + 1]:value(...)} ...

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

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

现在取决于你。

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

let calendar = google.calendar('v3');
  let auth = generateOAuth(cal)
  let insert = {
    "end": {
      "dateTime": booking.endDate.toISOString(),
  "timeZone": 'Europe/London' //NOTE We use Atlantic/Reykjavik to allow us to set UTC times in GOOGLE CALENDAR. https://blog.gerv.net/2012/11/the-rekjavik-trick/
    },
    "start": {
      "dateTime": booking.date.toISOString(),
  "timeZone": 'Europe/London' //NOTE We use Atlantic/Reykjavik to allow us to set UTC times in GOOGLE CALENDAR. https://blog.gerv.net/2012/11/the-rekjavik-trick/
    },
    "description": booking.service.name,
    "summary": `${booking.booker.fname} ${booking.booker.lname}`,
    "extendedProperties": {
      "private": {
        "bookingId": booking.date._id
      }
    }
  }

答案 2 :(得分:2)

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

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

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>

答案 3 :(得分:0)

在使用多选时,应将状态变量声明为数组

  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/

答案 4 :(得分:0)

我在这里使用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>
相关问题