React 函数式调用子组件
//这里Child是函数式组件 const Child = forwardRef((props, ref): JSX.Element => { //将子组件的方法暴露给父组件 useImperativeHandle(ref, () => { return { funcX: function () { console.log('执行我'); } }; }) return ( <div> <input defaultValue="ABCD" ></input> </div> ); });
import React, { Component, forwardRef, useImperativeHandle } from 'react' const Parent = (props): JSX.Element => { let childRef: any = React.useRef(); function handleOnClick() { if (childRef.current) { //ChildRef.current?.funcX(); childRef.current?.funcX(); } } return ( <div> <button onClick={handleOnClick}>click</button> <Child ref={childRef} /> </div> ); }; export default Parent;