React.FC中父组件调用子组件方法

https://blog.csdn.net/qq_36990322/article/details/109858890

1. 函数式和hooks写法

其实下面的缺点基本不算缺点了,因为函数式写法,下面算是简单的了。使用forwardRef只会让你的组件定义的更复杂

优点:
1、写法简单易懂
2、假如子组件嵌套了HOC,也可以指向真实子组件
缺点:
1、需要自定义props属性
2、需要自定义暴露的方法

父组件

 1 import React from 'react';
 2 import Child from './Child';
 3 
 4 const Parent = () => {
 5   let ChildRef = React.createRef();
 6 
 7   function handleOnClick() {
 8     ChildRef.current.func();
 9   }
10 
11   return (
12     <div>
13       <button onClick={handleOnClick}>click</button>
14       <Child onRef={ChildRef} />
15     </div>
16   );
17 };
18 
19 export default Parent;

子组件

 1 import React, { useImperativeHandle } from 'react';
 2 import { withRouter } from 'react-router-dom';
 3 
 4 const Child = props => {
 5   //用useImperativeHandle暴露一些外部ref能访问的属性
 6   useImperativeHandle(props.onRef, () => {
 7     return {
 8       func: func,
 9     };
10   });
11   function func() {
12     console.log('执行我');
13   }
14   return <div>子组件</div>;
15 };
16 
17 export default withRouter(Child);

2、函数式编程使用forwardRef抛出子组件的ref

 1 import {
 2   forwardRef,
 3   useState,
 4   useCallback,
 5   useImperativeHandle,
 6   createRef
 7 } from "react";
 8 
 9 export default function App() {
10   let c = createRef(null);
11   const handleChick = useCallback(() => {
12     console.log("父组件点击了");
13     c.current.add();
14   }, [c]);
15   return (
16     <div className="App">
17       <button onClick={handleChick}>点我运行子组件方法</button>
18       <Child ref={c} />
19     </div>
20   );
21 }
22 
23 const Child =  forwardRef((props, ref)=> {
24   const [num, setNum] = useState(0);
25   useImperativeHandle(
26     ref,
27     () => ({ add })
28   );
29   const add = () => {
30     setNum((num) => ++num);
31   };
32   return (
33     <div>
34       <button onClick={add}>这是子组件自己调用</button>
35       子组件的值:{num}
36     </div>
37   );
38 });

 

posted @ 2023-05-17 17:17  顺·  阅读(475)  评论(0编辑  收藏  举报