相关知识:
- useImperativeHandle
- forwardRef
相关代码:
获取子组件实例,由于这是函数组件,没有this因此不能整体获取,我们可以通过useImperativeHandle获取想要的变量或者方法。
- 父组件
import React, { useRef } from "react"; import Child from "./child"; function Parent(props) {const childRef = useRef();const changeChildText = () => {childRef.current.changeText();};return (<div id="parent" style={{ border: "1px solid #ccc", padding: 10 }}><h1>parent page</h1><button onClick={changeChildText}>通过父组件实现子组件点击事件</button><Child ref={childRef} /></div>); } export default Parent;
解释:父组件中通过属性ref,想要获取通过childRef这个ref存放子组件实例
子组件接收这个ref,然后给它身上绑定一些想要属性(也就是useImperativeHandle的第二个参数返回值) - 子组件
import React, { forwardRef, useImperativeHandle, useState } from "react";export default forwardRef((props, ref) => {const [text, setText] = useState("child page");useImperativeHandle(ref, () => {return {changeText,};});const changeText = () => {setText((prev) => {return prev + "★";});};return (<div id="child" style={{ background: "#f1f1f1", padding: 20 }}><h2>{text} <button onClick={changeText}>改变文本</button></h2></div>); });