简体   繁体   English

如何从 Ant design 的 Select/Option 组件中获取价值

[英]How to get value from Select/Option component from Ant design

I want to retrieve the value from my selection so I can make post requests.我想从我的选择中检索值,以便发出发布请求。 I have no problem getting from text input, but for some reason I can't get it from the drop down menu select.我从文本输入中获取没有问题,但由于某种原因,我无法从下拉菜单选择中获取它。 I end up getting a "TypeError: Cannot read property 'value' of undefined"我最终得到一个"TypeError: Cannot read property 'value' of undefined"

Here is the code I am using.这是我正在使用的代码。

import React from "react";
import { Form, Input, Button, Select } from "antd";

const { Option } = Select;

class ItemForm extends React.Component {

  handleFormSubmit = event => {
    event.preventDefault();
    const name = event.target.elements.name.value;
    const description = event.target.elements.description.value;
    const category = event.target.elements.category.value;
    console.log(name, description, this.refs.category.value);
  };

  render() {
    return (
      <div>
        <Form onSubmit={this.handleFormSubmit}>
          <Form.Item label="Form Layout" />
          <Form.Item label="Product Name">
            <Input name="name" placeholder="Ex: Organic Apple..." />
          </Form.Item>
          <Form.Item label="Description">
            <Input name="description" placeholder="Ex: Juicy organic apples!" />
          </Form.Item>
          <Form.Item label="Category">
            <Select name="category" placeholder="Please select a category">
              <Option value="Fruit">Fruit</Option>
              <Option value="Vegetable">Vegetable</Option>
              <Option value="Poultry">Poultry</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default ItemForm;

Use onChange which is fired when the value of the select changes. Use onChange which is fired when the value of the select changes. antd select documentation antd 选择文档

<Form.Item label="Category">
  <Select 
    onChange={(value) => {
      alert(value)
    }} 
    name="category" 
    placeholder="Please select a category">
      <Option value="Fruit">Fruit</Option>
      <Option value="Vegetable">Vegetable</Option>
      <Option value="Poultry">Poultry</Option>
  </Select>
</Form.Item>

working example工作示例

Something similar to the classic javascript approach, you intended to use, could be use getFieldValue .类似于您打算使用的经典 javascript 方法,可以使用getFieldValue
But coupling to coherent createRef , Form and Form.Item as below.但是耦合到一致的createRefFormForm.Item如下。

When getting values, remember to reference the Form.Item name and not the Input one ;-)获取值时,请记住引用Form.Item名称而不是Input名称;-)

I have created a sandbox demo hoping other people will enjoy or contribute.我创建了一个沙盒演示,希望其他人会喜欢或做出贡献。

import React from "react";
import { Form, Input, Button, Select } from "antd";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css"; //export default ItemForm;

const { Option } = Select;

class ItemForm extends React.Component {
  formRef = React.createRef();

  handleFormSubmit = event => {
    event.preventDefault();
    console.log("All field values", this.formRef.current.getFieldsValue());
    const name = this.formRef.current.getFieldValue("productName"); //OLD event.target.elements.name.value;
    const description = this.formRef.current.getFieldValue("description"); //OLD event.target.elements.description.value;
    const category = this.formRef.current.getFieldValue("category"); //OLD event.target.elements.category.value;
    console.log(name, description, category);
    alert(`${name}, ${description}, ${category}`);
  };

  render() {
    return (
      <div>
        <Form ref={this.formRef} onSubmit={this.handleFormSubmit}>
          <Form.Item label="Form Layout (Form.Item-createRef-getFieldValue Example)" />
          <Form.Item label="Product Name" name="productName">
            <Input name="name" placeholder="Ex: Organic Apple..." />
          </Form.Item>
          <Form.Item label="Description" name="description">
            <Input name="description" placeholder="Ex: Juicy organic apples!" />
          </Form.Item>
          <Form.Item label="Category" name="category">
            <Select name="category" placeholder="Please select a category">
              <Option value="Fruit">Fruit</Option>
              <Option value="Vegetable">Vegetable</Option>
              <Option value="Poultry">Poultry</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              onClick={this.handleFormSubmit}
            >
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
ReactDOM.render(<ItemForm />, document.getElementById("container"));

Managed it by using onChange as shown below this.通过使用 onChange 管理它,如下所示。

state = {
    status: ""
  };

          <Form.Item label="Status">
            <Select
              name="status"
              onChange={value => {
                this.setState({ status: value });
              }}
              placeholder="Please choose the status"
            >
              <Option value="new">New</Option>
              <Option value="open">Open</Option>
              <Option value="rejected">Rejected</Option>
              <Option value="deferred">Deferred</Option>
              <Option value="reopened">Reopened</Option>
            </Select>
          </Form.Item>

unlike what you would expect, in Ant Design Select you can't get the value by calling:与您所期望的不同,在 Ant Design Select 中,您无法通过调用获取值:

onChange={(e)=>console.log(e.target.value)}

no.不。 instead you get the value directly by just accessing the event itself, like this:相反,您只需访问事件本身即可直接获取值,如下所示:

onChange={(e)=>console.log(e)}

You can fix this as follows.您可以按如下方式修复此问题。 (Works fine for Antd) (适用于 Antd)

 <Select
    onChange={(text, index) => {
    console.log(index.children);
    }}
 >

A better and cleaner way to avoid this issue is to define all the form values and labels in an array and pass it into the .避免此问题的更好更简洁的方法是在数组中定义所有表单值和标签,并将其传递到 . Declare or use an onChange event and store the value of the event in your state.声明或使用 onChange 事件并将事件的值存储在您的状态中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM