antd在componentDidMount内部声明的<FormItem />生成的输入栏失效

新手上路,请多包涵

如果我在render外部声明了<FormItem />(如在componentDidMount内),然后再渲染它,生成的表单是不能被输入的,如:

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内部声明则可以正常使用,如:

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

请问会造成这个问题的原因是什么?
因为看起来两种方式几乎是一样的,以及是否能在render外部生成<FormItem />并且正常使用它?
谢谢 !

阅读 3.6k
1 个回答

我觉得可能是这个原因吧,因为这样写都是对的<FormItem><Input /></FormItem>
图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题