useImperativeHandle 父组件调用子组件方法

引入子组件

将ref传递过去

import React, { useEffect, useRef } from "react";
import Child from './components/Child'
import { connect } from "dva";
export default connect(state => {
    return {

    }
})(Impera)
// 父组件调用子组件方法
function Impera(props) {
    const ref = useRef()

    useEffect(() => {
        console.log('ref', ref);
        ref.current.onClick()
    }, [])
    return (
        
) }

引入useImperativeHandle和forwardRef

函数内是要调用的方法

import React, { forwardRef, useImperativeHandle } from "react";
export default forwardRef(Child)

function Child(props, ref) {

    const onClick = () => {
        console.log('我是子组件');
    }
    useImperativeHandle(ref, () => ({
        focus: () => {
            console.log('我是子组件的ref');
        },
        onClick,
    }), [])
    return (
        
) }

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