react+ts 父子组件传值(类组件、函数组件)

1.父组件为类组件

tips:classNavigateInterface是自己定义的interface 规定要接受什么值
// 引入interface
import {classNavigateInterface} from '@/assets/Interface'
// 引入react
import {Component,createRef} from "react";
// 引入弹窗Dialog
import ManifesInformationDialog from '@/components/dialog/ManifestInformation-dialog'

class SetOutFlight extends Component{
  ManifesInformationDialogRef:any
  constructor(props:classNavigateInterface){
    super(props)
    this.ManifesInformationDialogRef=createRef()
  }
  render(){
		return(
			
		)
	}
}

2.子组件为函数组件

tips:子组件接受里面一定要写一个ref:any, 最后导出的时候要用forwardRef包裹我们的组件,在useImperativeHandle的方法就可以让我们的父组件调用了
// 引入react
mport { useState,forwardRef, useImperativeHandle } from 'react';
// 引入interface 规范传值
import {ManifesInformationDialogIprops} from '@/assets/Interface';
const ManifesInformationDialog = (props:ManifesInformationDialogIprops,ref:any) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  useImperativeHandle(ref, () => ({
    getValues: () => {
      return ('hell word')
    },
    // 打开弹窗
    openDialog:() => {
      setIsModalVisible(true)
    }
  }))
  // 确定
  const handleOk = () => {
    props.handle()
    setIsModalVisible(false)
  }
  return(
		
我是子组件
) } export default forwardRef(ManifesInformationDialog)

你可能感兴趣的:(react,ts,react.js,javascript,前端)