关键点:子组件运用了,React.forwardRef,useImperativeHandle
React.memo可要可不要,是我上个分享的代码
import React, { useRef, useState, useImperativeHandle } from 'react';
interface ListProps {
list: string[];
id: number;
}
const List = React.forwardRef(function MyInput(props:ListProps, ref) {
const {list} = props;
const count = '这个是子组件变量'
useImperativeHandle(ref, () => ({
reload: () => {
// actionRef?.current?.reload(true)
console.log('调用了子组件的reload函数')
},
getCount:() => count
}));
return (
<div>
<ul>
{list.map((it, index) => <li key={index}>{it}</li>)}
</ul>
</div>
);
});
// true 不更新
// prev props上一个值
// next props下一个值
// prev.id === next.id 上一个id和下一个id不相等,子组件才更新
function checkItemEqual(prev, next) {
return prev.id === next.id
}
export default React.memo(List, checkItemEqual);
父组件调用子组件的函数,获取子组件的变量
import {
PageContainer,
} from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { useRef } from 'react';
import List from './components/List';
const TableList: React.FC = () => {
const ref = useRef(null);
const handleClick = () => {
ref.current.reload()
const parentCount = ref.current.getCount();
console.log('父组件获取子组件的变量count:', parentCount)
}
return (
<PageContainer>
<Button onClick={handleClick}>调用子组件的方法</Button>
<List ref={ref} id={5} list={['1','2','3']} />
</PageContainer>
);
};
export default TableList;