首页  >  问答  >  正文

FormItem ANTD中defaultValue或value无效的问题

<p>我尝试使用以下代码,但字段没有绑定。 onChange属性运行良好</p> <pre class="brush:php;toolbar:false;">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></pre> <p>我有什么遗漏吗?我什至使用了<code>input</code>而不是<code>Input</code></p> <p><strong>编辑</strong> 在<code>componentDidMount</code>方法中,我从API获取数据:</p> <pre class="brush:php;toolbar:false;">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 } }) })</pre> <p>我尝试使用<code>initialValue</code>,但只有在<code>constructor</code>方法中设置状态值时才有效。调用API时,更改不会反映出来。 </p>
P粉265724930P粉265724930396 天前427

全部回复(2)我来回复

  • P粉940538947

    P粉9405389472023-08-23 14:57:55

    你也可以使用钩子

    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>

    回复
    0
  • P粉078945182

    P粉0789451822023-08-23 12:33:30

    文档中指出:

    当数据从后端加载时,只需调用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)

    回复
    0
  • 取消回复