react v-18父组件调用子组件的方法和数据

版本

"react": "^18.1.0",
"react-dom": "^18.1.0",

父组件

import React, { useState, useRef, memo, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Card } from "antd";

import Childdren from './child/child';
function Dashboard() {
  let childRef:any = useRef(null);
  const handleClick = () => {
     console.log('子组件:', childRef.current)  //打印:{num: 999, add: ƒ}
    childRef.current.add() //调用
  }
  return (
        
             alert('传递了一个函数')} />
            
            
        
  );
}

export default Dashboard;

子组件 (通过useImperativeHandle() 抛出)

// props (类组件则使用this.props)
import React, { useImperativeHandle } from "react";
const Childdren = React.forwardRef((props:any, ref) => {
  useImperativeHandle(
    ref,
    () => ({ add,num }) //父组件通过ref获取值,要在这里抛出
  );
  const num = 999;
  const add = () => {
    console.log('我是子组件方法')
  };
  return (
    

父传子:{props.title}

); }); export default Childdren;

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