react+ts+hooks中组件之间的使用

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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容