包含form表单的子节点
import React, { useEffect, useImperativeHandle } from 'react'
import { Form, Input } from 'antd'
import styles from './index.module.scss'
type IProps = {
serverData?: any // 服务端数据,回显用
style?: { [x: string]: unknown }
}
const ChildNode = React.forwardRef(
({ serverData, style }: IProps, ref) => {
const [form] = Form.useForm()
useImperativeHandle(ref, () => ({
// 暴露给父组件的方法
validateFields,
getFieldsValue: () => {
const values = form.getFieldsValue()
return values
},
resetValues: () => {
form.resetFields()
},
}))
const validateFields = async () => {
try {
const values = await form.validateFields()
return values
} catch (e) {
return false
}
}
useEffect(() => {
if (serverData) {
form.setFieldsValue(serverData)
}
}, [serverData])
return (
<div className={styles.wrapper} style={style}>
<Form form={form} layout="vertical">
<Form.Item label="名称" name="name" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item label="编码" name="code" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Form>
</div>
)
},
)
export default ChildNode
1、React.forwardRef()
2、useImperativeHandle // 暴露给父组件的方法
父节点获取子节点的数据
import React, { useEffect, useState, createRef } from 'react'
import ChildNode from './ChildNode'
import { Button, Space } from 'antd'
type IProps = {
nextNodes: any[]
}
const ParentNode: React.FC<IProps> = ({ nextNodes }) => {
const [refs, setRefs] = useState<React.RefObject<any>[]>([])
// 创建refs
useEffect(() => {
if (!nextNodes) return
setRefs((fRefs) =>
Array(nextNodes?.length)
.fill(0)
.map((_, i) => fRefs[i] || createRef()),
)
}, [nextNodes])
// 校验 下个节点 表单信息
const validateFields = async () => {
try {
const values: any = []
let flag = true
for (let i = 0; i < refs.length; i++) {
const value = await refs[i]?.current?.validateFields()
console.log(`value${i}:`, value)
if (!value) flag = false
values.push(value)
}
return flag ? values : false
} catch {
return false
}
}
// 重置
const resetValues = () => {
for (let i = 0; i < refs.length; i++) {
refs[i]?.current?.resetValues()
}
}
// 获取 下个节点 表单信息
const getFieldsValue = () => {
const values: any = []
for (let i = 0; i < refs.length; i++) {
values.push(refs[i]?.current?.getFieldsValue())
}
return values
}
return (
<>
<Space>
<Button onClick={getFieldsValue}>获取数据</Button>
<Button onClick={resetValues}>重置</Button>
<Button onClick={validateFields}>校验</Button>
</Space>
{nextNodes?.length > 0 ? (
<>
{nextNodes.map((item, index) => {
return (
<ChildNode
style={{ marginBottom: 20 }}
ref={refs[index]}
key={index}
extData={item.nodeExtBase}
/>
)
})}
</>
) : (
<></>
)}
</>
)
}
export default ParentNode