前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react-开发经验分享-form表单组件中封装一个单独的input

react-开发经验分享-form表单组件中封装一个单独的input

作者头像
Mr. 柳上原
发布2018-12-12 13:28:54
2.8K0
发布2018-12-12 13:28:54
举报

在form表单中自定义封装一个input组件

如果不做处理

form表单提交时是获取不到这个自定义组件的数据的

这个坑对于新手来说

真的是个大坑

特别是对表单内的元素做提交不是很了解的人

用ant的ui框架来说明吧

一个基础的表单

// ant表单组件
import { Form, Select, Input, Button } from 'antd';

const FormItem = Form.Item;
const Option = Select.Option;

class App extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }

  handleSelectChange = (value) => {
    console.log(value);
    this.props.form.setFieldsValue({
      note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem
          label="Note"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 12 }}
        >
          {getFieldDecorator('note', {
            rules: [{ required: true, message: 'Please input your note!' }],
          })(
            <Input />
          )}
        </FormItem>
        <FormItem
          label="Gender"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 12 }}
        >
          {getFieldDecorator('gender', {
            rules: [{ required: true, message: 'Please select your gender!' }],
          })(
            <Select
              placeholder="Select a option and change input text above"
              onChange={this.handleSelectChange}
            >
              <Option value="male">male</Option>
              <Option value="female">female</Option>
            </Select>
          )}
        </FormItem>
        <FormItem
          wrapperCol={{ span: 12, offset: 5 }}
        >
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </FormItem>
      </Form>
    );
  }
}

App = Form.create({})(App);
export default App;

如果我们要自定义Select组件 在组件内部做后端数据请求 并渲染到子元素Option里 那么我们就需要从新封装自定义这个原生的Select组件

// 把Select单独提取出来
import React, { Component } from 'react';
import { Select, Icon } from 'antd';

import initialApi from './services/initialApi'; // 封装的后端接口请求

class SelectForm extends React.Component {
  constructor(props) {
    super(props);

    const value = props.value || {};
    this.state = {
      staffList: [], // 列表
    }
  }

  // 获焦时查询后端数据
  onFocus = () => {
    this.onRequstStaffData(this.props.organizationId);
  }

  // 查询数据
  onRequstStaffData = async (inquireId) => {
    let staffInquireData = {
      organizationId: `${inquireId}`,
      isDeleted: false,
      pageIndex: 0,
      pageSize: 9,
    } // 请求体
    let staffData = await initialApi.postStaff(staffInquireData);
    let staffList = staffData.extension || [];
    
    this.setState({
      staffList,
    })
  }

  // Select 数据变化时读取 value 值
  handleChange = (value) => {
    this.triggerChange(value);
  }

  // triggerChange 方法把获取到的 value 值返回给父级 form 表单 
  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    
    if(onChange) {
      onChange(changedValue);
    }
  }

  render() {
    return (
      <Select style={{width: 200}} suffixIcon={<Icon type="team" style={{color: 'rgba(0, 0, 0, 0.38)'}} />} onChange={this.handleChange}
        defaultValue={`${this.props.user.profile.name}`} notFoundContent="没有查询到数据!" onFocus={this.onFocus}
      >
        <OptGroup label="Manager">
          {this.state.staffList.map((item, index) => {
            return (
              <Option key={item.id} value={item.trueName}>{item.trueName}</Option>
            )
          })}
        </OptGroup>
      </Select>
    )
  }
}

export default SelectForm;

并把这个自定义组件导入到原来的form表单里

// 修改后的ant表单组件
import { Form, Select, Input, Button } from 'antd';
import SelectForm from './selectForm';

const FormItem = Form.Item;

class App extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem
          label="Note"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 12 }}
        >
          {getFieldDecorator('note', {
            rules: [{ required: true, message: 'Please input your note!' }],
          })(
            <Input />
          )}
        </FormItem>
        <FormItem
          label="Gender"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 12 }}
        >
          {getFieldDecorator('gender', {
            rules: [{ required: true, message: 'Please select your gender!' }],
          })(
            <SelectForm organizationId={'传给SelectForm的值'} user={'传给SelectForm的值'} />
          )}
        </FormItem>
        <FormItem
          wrapperCol={{ span: 12, offset: 5 }}
        >
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </FormItem>
      </Form>
    );
  }
}

const WrappedApp = Form.create()(App);
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.11.14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档