使用父组件使用hooks调用子组件中的方法
时间: 2023-10-13 07:06:43 浏览: 50
可以使用useImperativeHandle钩子函数来向外暴露子组件的方法,然后在父组件中通过ref获取子组件实例并调用该方法。具体实现可以参考以下代码:
子组件:
```jsx
import { useImperativeHandle, forwardRef } from "react";
const ChildComponent = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
childMethod() {
console.log("Child component method is called");
},
}));
return <div>Child Component</div>;
});
export default ChildComponent;
```
父组件:
```jsx
import { useRef } from "react";
import ChildComponent from "./ChildComponent";
const ParentComponent = () => {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.childMethod();
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Call Child Component Method</button>
</div>
);
};
export default ParentComponent;
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)