欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

React学习——通过模态框中的表单学习父子组件之间传值

程序员文章站 2023-04-07 12:54:37
import { Button, Modal, Form, Input, Radio } from 'antd'; const CollectionCreateForm = Form.create({ name: 'form_in_modal' })( // eslint-disable-next-... ......
import { button, modal, form, input, radio } from 'antd';

const collectioncreateform = form.create({ name: 'form_in_modal' })(
  // eslint-disable-next-line
  class extends react.component {
    render() {
      const { visible, oncancel, oncreate, form } = this.props;
      const { getfielddecorator } = form;
      return (
        <modal
          visible={visible}
          title="create a new collection"
          oktext="create"
          oncancel={oncancel}
          onok={oncreate}
        >
          <form layout="vertical">
            <form.item label="title">
              {getfielddecorator('title', {
                rules: [{ required: true, message: 'please input the title of collection!' }],
              })(<input />)}
            </form.item>
            <form.item label="description">
              {getfielddecorator('description')(<input type="textarea" />)}
            </form.item>
            <form.item classname="collection-create-form_last-form-item">
              {getfielddecorator('modifier', {
                initialvalue: 'public',
              })(
                <radio.group>
                  <radio value="public">public</radio>
                  <radio value="private">private</radio>
                </radio.group>,
              )}
            </form.item>
          </form>
        </modal>
      );
    }
  },
);

class collectionspage extends react.component {
  state = {
    visible: false,
  };

  showmodal = () => {
    this.setstate({ visible: true });
  };

  handlecancel = () => {
    this.setstate({ visible: false });
  };

  //获得表单数据,并且打印出来
  handlecreate = () => {
    const form = this.formref.props.form;
    form.validatefields((err, values) => {
      if (err) {
        return;
      }

      console.log('received values of form: ', values);
      form.resetfields();
      this.setstate({ visible: false });
    });
  };

  saveformref = formref => {
    this.formref = formref;
  };

  render() {
    return (
      <div>
        <button type="primary" onclick={this.showmodal}>
          new collection
        </button>
        <collectioncreateform
          //父子组件之间传递表单数据
          wrappedcomponentref={this.saveformref}
          visible={this.state.visible}
          oncancel={this.handlecancel}
          oncreate={this.handlecreate}
        />
      </div>
    );
  }
}

reactdom.render(<collectionspage />, mountnode);