在进行React开发时,函数组件是比较方便的,由于函数组件没有this指针,因此如果想在父组件里调用函数型子组件的方法,就需要用到React.useImperativeHandle 这个帮助函数。
办法要点:
1、在子组件中,使用useImperativeHandle函数将子组件中的方法暴露出去,在导出时使用forwardRef包裹导出的组件;
2、理解 useImperativeHandle 函数的两个参数:
第一个参数ref即是函数组件自带的参数(props,ref)中的 ref。
第二个参数是一个函数,函数返回的对象就是父组件中的 childRef.current
3、需要暴露方法的组件,在导出的时候,一定要加上forwardRef进行包裹
export default forwardRef(Son)
子组件示例:
import React, { useState, forwardRef, useImperativeHandle } from "react"
function Son(props, ref) {
const [a, setA] = useState(1);
const [b, setB] = useState(2);
function sonFunc() {
console.log("我是儿子中的方法")
}
useImperativeHandle(ref, () => {
return {
sonFunc,
setA,
a: a,
b
}
});
return (
<div id="headerBox">
{a}
</div>
)
}
export default forwardRef(Son)
4、在父组件中使用useRef(),并对子组件进行绑定 ref 。
打印的childRef中有一个属性叫做current,current就是子组件暴露出来的实例句柄。
点击父亲的执行按钮,就可以通过childRef.current.sonFunc()执行子组件的方法sonFun,也可以执行儿子中的改变state的方法setA,从而通过父组件来改变子组件的状态值。
调用者(父组件)示例:
import React, { useState, useRef} from "react";
import Son from "./Son";
function Father(props, ref) {
const childRef = useRef(null);
function printRef() {
console.log(childRef );
}
function doSonFunc() {
childRef.current.sonFunc();
childRef.current.setA(456);//把子组件中的a从1改变为456
}
return (
<div className="Home">
<Son ref={childRef } />
<button onClick={printRef}>打印ref</button>
<button onClick={doSonFunc}>执行儿子的方法</button>
</div>
)
}
export default Father
这个方法不仅是可以用来调用儿子的方法,对于儿子的状态属性,也是能够传过来的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)