React Hooks中父組件中調用子組件方法
使用到的hooks-- useImperativeHandle,useRef
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/* child子組件 */
// https://reactjs.org/docs/hooks-reference.html#useimperativehandle
import
{useState, useImperativeHandle} from
'react'
;
...
// props子組件中需要接受ref
const ChildComp = ({cRef}) => {
const [val, setVal] = useState();
// 此處注意useImperativeHandle方法的的第一個參數是目標元素的ref引用
useImperativeHandle(cRef, () => ({
// changeVal 就是暴露給父組件的方法
changeVal: (newVal) => {
setVal(newVal);
}
}));
...
return
(
<div>{val}</div>
)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/* FComp 父組件 */
import
{useRef} from 'react;
...
const FComp = () => {
const childRef = useRef();
const updateChildState = () => {
// changeVal就是子組件暴露給父組件的方法
childRef.current.changeVal(99);
}
...
return
(
<>
{
/* 此處注意需要將childRef通過props屬性從父組件中傳給自己 cRef={childRef} */
}
<ChildComp cRef={childRef} />
<button onClick={updateChildState}>觸發子組件方法</button>
</>
)
}
|
方法二、參考react官方文檔:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
{useState, useImperativeHandle,forwardRef} from
'react'
;
// props子組件中需要接受ref
let
ChildComp = (props,ref) => {
// 此處注意useImperativeHandle方法的的第一個參數是目標元素的ref引用
useImperativeHandle(ref, () => ({
// changeVal 就是暴露給父組件的方法
changeVal: (newVal) => {
}
}));
return
(
<div>{val}</div>
)
}
ChildComp = forwardRef(ChildComp)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/* FComp 父組件 */
import
{useRef} from
'react'
;
const FComp = () => {
const childRef = useRef();
const updateChildState = () => {
// changeVal就是子組件暴露給父組件的方法
childRef.current.changeVal(99);
}
return
(
<>
<ChildComp ref={childRef} />
<button onClick={updateChildState}>觸發子組件方法</button>
</>
)
}
|