formily自定义组件开发

自定义组件仅需要支持标准的 onChange 和 value 即可

本例子采用 formily + antd + react 实现
sandbox参考例子

// Form 部分
import React from "react";
import ReactDOM from "react-dom";
import {
  SchemaForm,
  SchemaMarkupField as Field,
  FormButtonGroup,
  Submit
} from "@formily/antd";
import { Upload, Row, Col, Input, DatePicker } from "antd";
import moment from "moment";
import "antd/dist/antd.css";

const App = () => {
  return (
    <SchemaForm
      labelCol={3}
      wrapperCol={21}
      components={{ CustomUpload, CustomComponent }}
      onSubmit={values => {
        console.log(values);
      }}
    >
      <Field
        name="uploadResponse"
        title="图片"
        x-component="CustomUpload"
        x-component-props={{
          listType: "picture-card",
          action: "//www.mocky.io/v2/5cc8019d300000980a055e76"
        }}
      />
      <Field
        name="customComponent"
        title="自定义组件"
        x-component="CustomComponent"
        x-component-props={{
          initValue: { input: "111", date: moment() }
        }}
      />
      <FormButtonGroup offset={3}>
        <Submit />
      </FormButtonGroup>
    </SchemaForm>
  );
};
ReactDOM.render(<App />, document.getElementById("root"));
// 自定义上传组件
const CustomUpload = props => {
  const { onChange, ...rest } = props;
  const handleChange = data => {
    if (data.file.status === "done") {
      console.log(data);
      onChange(data.file.response);
    }
  };
  return (
    <Upload onChange={handleChange} {...rest}>
      <div>上传</div>
    </Upload>
  );
};
// 自定义其他组件
const CustomComponent = props => {
  const { onChange, initValue } = props;
  const customValue = { input: "", datePicker: "" };
  const handleChange = (data, type) => {
    if (type === "input") {
      customValue.input = data;
    } else {
      customValue.datePicker = data;
    }
    onChange(customValue);
  };
  return (
    <Row gutter={16}>
      <Col span={12}>
        <Input
          defaultValue={initValue.input}
          onChange={e => handleChange(e.target.value, "input")}
        />
      </Col>
      <Col span={12}>
        <DatePicker
          defaultValue={initValue.date}
          style={{ width: "100%" }}
          onChange={value => handleChange(value, "date")}
        />
      </Col>
    </Row>
  );
};

友情链接

antd4官方文档
formily官方文档

你可能感兴趣的:(前端,reactjs,javascript)