鍍金池/ 問(wèn)答/HTML/ antd在componentDidMount內(nèi)部聲明的<FormItem

antd在componentDidMount內(nèi)部聲明的<FormItem />生成的輸入欄失效

如果我在render外部聲明了<FormItem />(如在componentDidMount內(nèi)),然后再渲染它,生成的表單是不能被輸入的,如:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Icon, Input, Button, Checkbox } from "antd";
const FormItem = Form.Item;

class CustomizedForm extends React.Component {
  handleSubmit = e => {
    e.preventDefault();
  };
  state = {
    ready: false
  };
  componentDidMount() {
    const { getFieldDecorator } = this.props.form;
    this.formItem = (
      <FormItem>{getFieldDecorator("field1")(<Input />)}</FormItem>
    );
    this.setState({ ready: true });
  }
  render() {
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        {this.state.ready === true ? this.formItem : null}
      </Form>
    );
  }
}

const WrappedNormalLoginForm = Form.create()(CustomizedForm);

ReactDOM.render(
  <WrappedNormalLoginForm />,
  document.getElementById("container")
);

CodeSandBox

但是在render內(nèi)部聲明則可以正常使用,如:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Icon, Input, Button, Checkbox } from "antd";
const FormItem = Form.Item;

class CustomizedForm extends React.Component {
  handleSubmit = e => {
    e.preventDefault();
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    this.formItem = (
      <FormItem>{getFieldDecorator("field1")(<Input />)}</FormItem>
    );
    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        {this.formItem}
      </Form>
    );
  }
}

const WrappedNormalLoginForm = Form.create()(CustomizedForm);

ReactDOM.render(
  <WrappedNormalLoginForm />,
  document.getElementById("container")
);

CodeSandBox

請(qǐng)問(wèn)會(huì)造成這個(gè)問(wèn)題的原因是什么?
因?yàn)榭雌饋?lái)兩種方式幾乎是一樣的,以及是否能在render外部生成<FormItem />并且正常使用它?
謝謝 !

回答
編輯回答
撿肥皂

我覺(jué)得可能是這個(gè)原因吧,因?yàn)檫@樣寫都是對(duì)的<FormItem><Input /></FormItem>
圖片描述

2018年7月17日 02:11