Class组件可以通过配置ref,父组件就可以调用到子组件的function和data
父组件
import { FC, useState, useEffect, useRef } from 'react';
const IndexPage: FC = () => {
const classListRef = useRef();
return (
<>
<Button
onClick={(dim) => {
classListRef?.current?.queryList({
id: dim.id,
});
}}
</Button>
<MyClassList ref={classListRef} />
</>
)
}
Class子组件
class MyClassList extends React.PureComponent<ListProps,ListState> {
queryList = (params?) => {
....
}
render() {
return (
<>
....
</>
)
}
}
export default MyClassList;
function子组件不能直接使用ref
- 需要React.forwardRef()包一层
- 通过useImperativeHandle(props.listRef, () => ({ ... })配置暴露给父组件的function和data
父组件
import { FC, useState, useEffect, useRef } from 'react';
const IndexPage: FC = () => {
const hookListRef = useRef();
return (
<>
<Button
onClick={() => {
hookListRef.current?.cancelSelectedDimension();
}}
</Button>
<MyHookList ref={hookListRef} />
</>
)
}
子组件
import React, { FC, useImperativeHandle } from 'react';
type ItemDataType = {
id: number;
name?: string;
// 更多属性...
}
const MyHookList: FC<ListProps> = (props) => {
useImperativeHandle(props.listRef, () => ({
// 暴露给父组件的data
selectedDimension: selectValue,
// 暴露给父组件的方法
cancelSelectedDimension: () => {
setSelectValue(undefined)
}
}));
const [selectValue, setSelectValue] = useState<ItemDataType>();
return (
<>
....
</>
)
}
export default React.forwardRef((props: ListProps, ref?: any) => {
return <MyHookList {...props} listRef={ref} />;
});