使用React提供的ref来实现父子组件通信
类组件写法:
子组件
import React from "react";
export default class ClildCom extends React.Component {
const triggerFunction = () => {
alert('子组件的方法被触发')
}
render (){
return <div></div>
}
}
父组件:
import React from "react";
import ClildCom from './ClildCom';
export default class ParentCom extends React.Component {
render () {
const ChildRef = React.createRef();
return (
<div>
<ClildCom ref = {ChildRef} />
<div onClick={() => {ChildRef.current.triggerFunction()}}>调用子组件方法</div>
</div>
);
}
}
函数组件Hooks写法
子组件
import React, {useEffect, useImperativeHandle, forwardRef} from 'react';
function ChildCom(props, ref) {
useImperativeHandle(ref, () => ({
method1, // 需要暴露给父组件的方法
method2,
}));
const method1 = () => {
alert('子组件方法1')
};
const method2 = project => {
alert('子组件方法2')
};
return (
<div>
<div/>
);
}
export default forwardRef(ChildCom);
父组件:
复制代码
import React, {useRef} from 'react';
// 引用子组件
import ChildCom from './ChildCom';
function ParentCom() {
const ref = useRef();
return (
<>
<ChildCom ref={ref}/>
<div onClick={() =>{
ref.current.method1();
ref.current.method2();
}}>调用子组件方法</div>
</>
);
}
export default ParentCom;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)