【问题标题】:Reactjs how to get value from selected elementReactjs如何从选定元素中获取值
【发布时间】:2018-12-04 21:28:57
【问题描述】:

所以我有这个代码可以发布到我的后端 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>
    )
  }
}

【问题讨论】:

标签: forms reactjs drop-down-menu axios


【解决方案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)} />

【讨论】:

  • 此代码不适用于 Ant Design 的 Cascader。不过谢谢。
【解决方案2】:

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

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

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

【讨论】:

  • 这很完美!我今天读了几个小时的文档,我一直无法说出答案。谢谢谢谢。
  • 很高兴能帮上忙!
  • 很抱歉,我的代表低于 15 岁,所以我无法对此进行投票 ?
猜你喜欢
  • 2014-03-12
  • 2017-05-14
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
相关资源
最近更新 更多