函数式组件(useRef/forwardRef/useImperativeHandle):
父组件:
- import { Button } from 'antd'
- import React, { useRef } from 'react'
- import ChildElement from './ChildElement'
-
- const Parent = () => {
- const childRef = useRef(null)
- const useChildFun = () => {
- childRef.current.getChildMessage()
- }
- return (
- <>
- <ChildElement ref={childRef} />
- <Button onClick={useChildFun}>使用子组件方法Button>
- >
- )
- }
-
- export default Parent
子组件
- import React, { forwardRef, useImperativeHandle } from 'react'
-
- const ChildElement = forwardRef((_props, ref) => {
- const getChildMessage = () => {
- console.log(123456789)
- }
- useImperativeHandle(ref, () => ({
- getChildMessage
- }))
- return <div>Childdiv>
- })
-
- export default ChildElement