zy-react-library/src/components/FormBuilder/FormBuilder.js

113 lines
3.0 KiB
JavaScript
Raw Normal View History

2025-12-15 15:26:56 +08:00
import { Button, Col, Form, message, Row, Space, Spin } from "antd";
2025-12-26 11:49:29 +08:00
import { useEffect, useState } from "react";
2025-10-22 14:43:42 +08:00
import FormItemsRenderer from "./FormItemsRenderer";
/**
* 表单构建器组件
*/
const FormBuilder = (props) => {
const {
values,
options,
gutter = 24,
span = 12,
labelCol = { span: 4 },
useAutoGenerateRequired = true,
showActionButtons = true,
submitButtonText = "提交",
cancelButtonText = "取消",
showSubmitButton = true,
showCancelButton = true,
customActionButtons,
extraActionButtons,
2025-11-08 08:50:36 +08:00
loading = false,
2025-10-22 14:43:42 +08:00
...restProps
} = props;
2025-12-26 11:49:29 +08:00
const [pageWidth, setPageWidth] = useState(window.innerWidth);
const getPageWidth = () => {
const pageDom = document.querySelector("#page");
if (!pageDom)
return;
setPageWidth(pageDom.offsetWidth);
};
useEffect(() => {
const timer = setTimeout(() => {
getPageWidth();
}, 0);
2025-12-26 13:50:53 +08:00
if (showActionButtons) {
window.addEventListener("resize", getPageWidth);
}
2025-12-26 11:49:29 +08:00
return () => {
2025-12-26 13:50:53 +08:00
if (showActionButtons) {
window.removeEventListener("resize", getPageWidth);
}
2025-12-26 11:49:29 +08:00
clearTimeout(timer);
};
2025-12-26 13:50:53 +08:00
}, [showActionButtons]);
2025-12-26 11:49:29 +08:00
const handleCancel = () => {
window.history.back();
};
2025-10-22 14:43:42 +08:00
return (
2025-11-08 08:50:36 +08:00
<Spin spinning={loading}>
<Form
labelCol={labelCol}
scrollToFirstError
wrapperCol={{ span: 24 - labelCol.span }}
initialValues={values}
onFinishFailed={() => {
message.error("请补全必填项");
}}
2025-11-08 08:50:36 +08:00
style={{ width: `calc(100% - ${gutter * 2}px)`, margin: `0 auto` }}
{...restProps}
>
<Row gutter={gutter}>
<FormItemsRenderer
options={options}
labelCol={labelCol}
span={span}
2025-12-02 17:43:11 +08:00
gutter={gutter}
2025-11-08 08:50:36 +08:00
useAutoGenerateRequired={useAutoGenerateRequired}
initialValues={values}
/>
</Row>
2025-11-08 08:50:36 +08:00
{showActionButtons && (
2025-12-26 11:49:29 +08:00
<>
<div style={{ height: "32px" }}></div>
2025-12-24 15:45:07 +08:00
<Row
2025-12-26 11:49:29 +08:00
style={{ textAlign: "center", backgroundColor: "rgb(241, 241, 242)", padding: "10px 0", position: "fixed", bottom: "0", width: pageWidth, margin: "0 -44px" }}
2025-12-24 15:45:07 +08:00
>
<Col span={24} style={{ textAlign: "center" }}>
{customActionButtons || (
<Space>
{showSubmitButton && (
<Button type="primary" htmlType="submit">
{submitButtonText}
</Button>
)}
{extraActionButtons}
{showCancelButton && (
<Button onClick={handleCancel}>
{cancelButtonText}
</Button>
)}
</Space>
)}
</Col>
</Row>
2025-12-26 11:49:29 +08:00
</>
2025-11-08 08:50:36 +08:00
)}
</Form>
</Spin>
2025-10-22 14:43:42 +08:00
);
};
FormBuilder.displayName = "FormBuilder";
export default FormBuilder;