Reactjs如何从选定的元素中获取价值

时间:2018-06-26 08:19:43

标签: forms reactjs drop-down-menu axios

所以我有这段代码可发布到我的后端API。正常形式完全正常;我设法发布到我的数据库。因此,我从Ant Design CSS Framework中添加了一个Cascader,每次选择该值时,都会产生错误

  

TypeError:无法读取未定义的属性“值”

代码如下:

import React from 'react';
import axios from 'axios';
import { Button, Cascader, Form, Input, Modal } from 'antd';

const FormProduct = Form.Item;
const computerType = [
  {
    value: 'computer',
    label: 'Computer',
  },
  {
    value: 'laptop',
    label: 'Laptop',
  }
]

export default class FormInventory extends React.Component {
  state = {
    category: '',
    productname: '',
  };

  handleCategoryChange = event => { this.setState({ category: event.target.value }) }
  handleProductNameChange = event => { this.setState({ productname: event.target.value }) }

  handleSubmit = event => {
    event.preventDefault();

    axios.post('myapi',
      {
        category: this.state.category,
        productname: this.state.productname,
      })
      .then(
        function success() {
          const modal = Modal.success({
            title: 'Success',
            content: 'Data successfully add',
          });
          setTimeout(() => modal.destroy(), 2000);
        }
      )
  }

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormProduct {...formProductLayout} label="Computer Category">
          <Cascader options={computerType} category={this.state.value} onChange={this.handleCategoryChange} />
        </FormProduct>
        <FormProduct {...formProductLayout} label="Product Name">
          <Input type="text" productname={this.state.productname} onChange={this.handleProductNameChange} />
        </FormProduct>
        <FormProduct wrapperCol={{ span: 12, offset: 2 }}>
          <Button type="primary" htmlType="submit">
            Add Item
          </Button>
        </FormProduct>
      </Form>
    )
  }
}

2 个答案:

答案 0 :(得分:1)

您需要在构造函数中绑定事件处理程序,或使用箭头功能。

选项1:绑定

constructor(props) {
  // This binding is necessary to make `this` work in the callback
  this.handleClick = this.handleClick.bind(this);
}

选项2:箭头功能

<Input onChange={(e) => this.handleChange(e)} />

答案 1 :(得分:1)

根据antd文档,您不需要event.targethttps://ant.design/components/cascader/

handleCategoryChange = value => { this.setState({ category: value }) }

上面的代码可以正常工作。