how to get field value on change for FormItem in antd

前端 未结 3 1773
无人共我
无人共我 2021-02-13 16:48

I am having a hard time with antd\'s form. I have this select field in this form and I want to get the value from it onChange but somehow not getting it to work properly.

<
相关标签:
3条回答
  • 2021-02-13 16:55

    I realize this is super late, but I think this might be what OP was looking for:

    https://github.com/react-component/form/blob/3b9959b57ab30b41d8890ff30c79a7e7c383cad3/examples/server-validate.js#L74-L79

    To set fields on a form dynamically, e.g. in a child via a callback, you could use

        this.props.form.setFields({
          user: {
            value: values.user,
            errors: [new Error('forbid ha')],
          },
        }); 
    

    in a parent defined handleSelect method you called from the child on a selected value. you can alternatively use setFieldsValue if you dont want to pass an error field

    0 讨论(0)
  • 2021-02-13 17:05

    A quick response, and hopefully a quick solution. Rather than using onChange you may want to use onSelect/onDeselect handlers, per the documentation (https://ant.design/components/select/):

    <Select onSelect={handleCategoryChange} .../>
    

    I have found also that SELECT and other input components, due to their custom html nature operate differently, and so in my forms, I have often created them as dummy fields that are using to alter text/hidden inputs in order to achieve the desired behaviours in complex forms.

    Either I am doing something wrong, or the ANT way is mildly annoying.

    Hope this helps.

    0 讨论(0)
  • 2021-02-13 17:15

    Try this:

    <FormItem
      {...formItemLayout}
      label={fieldLabels.qcategoryid}
      validateStatus={categoryError ? "error" : ""}
      help={categoryError || ""}
    >
      {getFieldDecorator("qcategoryid", {
        rules: [{ required: true, message: "Please select Category!" }]
      })(<Select onChange={this.handleCategoryChange}>{categoryOptions}</Select>)}
    </FormItem>
    

    And on the handleCategoryChange function

    handleCategoryChange = (value, e) => {
      this.setState({
        categorySelected: value,
        categoryname: e.props.name
      });
    };
    

    Basically, changing the onChange from the getFieldDecorator helper to the Select, so it doesn't mess with antd's natural behavior, but gets the value and change on state

    I've based this answer on the code to the registration form on their website. Specifically, the handleWebsiteChange function

    https://ant.design/components/form/#components-form-demo-register

    0 讨论(0)
提交回复
热议问题