子组件把ref暴露给父组件,父组件调用子组件的方法和变量
父组件
// class组件
import React, {Component} from 'react';
import Children from "../components/children";
export default class Test extends Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
}
render() {
return (
<div>
我是父组件
<p onClick={() => console.log(this.buttonRef)}>我要获取子组件button的ref</p>
<Children ref={this.buttonRef}>我是子组件啊!!!</Children>
</div>
)
}
}
// hook组件
import React, { useRef } from 'react';
import Children from "../components/children";
export default function Test(props) {
const buttonRef = useRef();
useEffect(async () => {
打印即可调用子组件的方法和变量
console.log(buttonRef.current )
}, []);
return (
<div>
我是父组件
<p onClick={() => console.log(buttonRef)}>我要获取子组件button的ref</p>
<Children ref={buttonRef}>我是子组件啊!!!</Children>
</div>
);
}
子组件
import React, {useRef, useImperativeHandle} from 'react';
const Children = React.forwardRef((props, ref) => {
const refModal = useRef();
const showModal = () => {
console.log('我是子组件的方法')
};
useImperativeHandle(ref, () => ({
// changeVal 就是暴露给父组件的方法
showModal: showModal,
}));
return (
<button ref={refModal }>
child
</button>
)
});
export default Children;
如果一直出不来,就要考虑看看是不是子组件的ref拼写错了,或者写错了位置,我就因为把ref写到antd的<Modal><Modal/>上而出错了,我最后在<Modal><Modal/>外层添加了一层div,并把ref绑定到div上,最后终于对了,我也是好久才发现的,呜呜!!!
网友评论