0%

React Hooks 中父组件中调用子组件方法

需求

React 父组件主动触发子组件的方法

解决方法

主要用到了 useRef useImperativeHandle forwardRef 3 个方法

子组件代码如下,用 useImperativeHandle 将方法暴露出去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { MyComponent } from 'my-component';

const Children = forwardRef((props, ref) => {
const [myState, setMyState] = useState([]);
useImperativeHandle(
ref,
() => ({
myState,
setMyState,
}),
[myState]
);
return <MyComponent {...props} />;
});

export default Children;

父组件代码如下,主要是用 useRef

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React, { useState, useRef } from 'react';
import Children from 'children';

const Parent = (props, ref) => {
const [ref] = useRef(null);

const setState = (params) => {
ref.current.setMyState(params);
};

const getState = () => {
console.log('getState :>> ', ref.current.myState);
};

return (
<div>
<div
onClick={() => {
setState(1111);
}}>
setState
</div>
<div
onClick={() => {
getState();
}}>
getState
</div>
<Children ref={ref} />
</div>
);
};

后记

这个最好看一下react官方文档