版本
javascript
"react": "^18.1.0",
"react-dom": "^18.1.0",
父组件
javascript
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 (
<Card style={{ minHeight: "calc(100vh - 64px)" }}>
<Childdren ref={childRef} title={'我是父组件的数据'} num={123} fun={() => alert('传递了一个函数')} />
<button onClick={handleClick}>父组件调子组件方法</button>
</Card>
);
}
export default Dashboard;
子组件 (通过useImperativeHandle() 抛出)
javascript
// 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 (
<div>
<h1>父传子:{props.title}</h1>
<button >这是子组件</button>
</div>
);
});
export default Childdren;