1.父组件调用子组件的方法
定义父组件:
import React, { useEffect, useState, useRef } from 'react'
interface ParentProps {
// 父组件回调函数类型定义
onChildData: (data?: any) => void
}
const DnsView: React.FC<ParentProps> = () => {
const handleEdit = (value: any) => {
childRef.current.showModal(true, value)
}
//子组件提交的方法
const getChildData = () => {
getData()
}
return <div>
<Button
type='text'
style={{ color: '#1677ff' }}
onClick={() => handleEdit(record)}
>
编辑
</Button>
<Add ref={childRef} onChildData={getChildData}></Add>
</div>
}
export default DnsView
定义子组件:
import React, {
useEffect,
useState,
forwardRef,
useImperativeHandle
} from 'react'
import {Button, message, Modal } from 'antd'
interface childType {
onChildData: (data?: any) => void
}
const DnsViewAdd = (props: childType, ref: any): any => {
const handleOk = async () => {
try {
//将子组件的事件传递给父组件
props.onChildData()
} catch (errorInfo) {
console.log('Failed:', errorInfo)
}
}
//父组件要调用的子组件的方法
const showModal = (isEdit: boolean, item: any) => {
setOpen(true)
}
const handleCancel = () => {
setOpen(false)
}
//将父组件要调用的方法,暴露出去
useImperativeHandle(ref, () => ({
showModal
}))
return (
<Modal
open={open}
onOk={handleOk}
onCancel={handleCancel}
title='创建视图'
centered
>
<div
className='dnsViewAdd'
style={{ height: '60vh', overflowY: 'auto' }}
>
子组件内容
</div>
</Modal>
)
}
export default forwardRef(DnsViewAdd)
网友评论