需求
React 父组件主动触发子组件的方法
解决方法
主要用到了 useRef
useImperativeHandle
forwardRef
3 个方法
子组件代码如下,用 useImperativeHandle
将方法暴露出去
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
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 官方文档