簡體   English   中英

默認值或值不適用於 FormItem ANTD

[英]defaultValue or value not working on FormItem ANTD

我嘗試使用以下代碼,但該字段永遠不會被綁定。 onChange 屬性運行良好

const { getFieldDecorator, getFieldError, isFieldTouched } = this.props.form;
const NameError = isFieldTouched("Name") && getFieldError("Name");

<FormItem validateStatus={NameError ? "error" : ""} help={NameError || ""}>
  {getFieldDecorator("Name", {
    //initialValue: this.state.Data.Name,
    rules: [{ required: true, message: "Please input the component name!" }]
  })(
    <Input
      className="form-control"
      type="text"
      name="Name"
      defaultValue={this.state.Data.Name}
      onChange={this.onChange}
    />
  )}
</FormItem>

我錯過了什么嗎? 我什至使用input而不是Input

編輯componentDidMount方法上,我從 API 獲取數據:

fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
          .then(results=>{
            return results.json()
          })
          .then(data=>{

            this.setState({
                Data: {
                    Id: data.field.Id,
                    Name: data.field.Name,
                    Description: data.field.Description,
                    Value: data.field.Value
                }
              })

          })

我嘗試使用initialValue ,但它僅在constructor方法上設置狀態值時才有效。 調用 API 時,不會反映更改。

文檔指出

您不能通過 value defaultValue 屬性設置表單控件的值,而應該使用getFieldDecorator 中的 initialValue設置默認值。

您不應該手動調用 setState,請使用 this.props.form.setFieldsValue以編程方式更改值。

所以你只需要在后端加載數據時調用setFieldsValue

fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
      .then(results=>{
        return results.json()
      })
      .then(data=>{

        this.props.form.setFieldsValue({
                Id: data.field.Id,
                Name: data.field.Name,
                Description: data.field.Description,
                Value: data.field.Value
          })
      })

或者更短,如果后端的data.field完全匹配字段名稱:

this.props.form.setFieldsValue(data.field)

對於類組件 V4:

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

  componentDidMount() {
    this.formRef.current.setFieldsValue({
      username: 'Bamboo',
    });
  }

  render() {
    return (
      <Form ref={this.formRef}>
        <Form.Item name="username" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      </Form>
    );
  }
}

你也可以使用鈎子

import { Form } from "antd"

const [form] = Form.useForm();

 fetch('api')
      .then(results=>{
        return results.json()
      })
      .then(data=>{
        form.setFieldsValue({
           sample: data.dataYouWant
        });


<Form form = {form}>
   <Form.Item name = "sample">
       <Input />
   </Form.Item>
</Form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM