函数组件中:父组件想要访问子组件中的方法和数据;
子组件使用forwardRef做转发,使用useImperativeHandle把方法暴漏出去,在父组件中即可访问到;
import { useImperativeHandle, forwardRef } from 'react';
const Children = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
getList: (params = {}) => {
getDataList(params);
},
}));
const getDataList = (params) => {
console.log('父组件传入的参数:',params)
}
}
import { useRef } from 'react';
let ChildrenRef = useRef();
const handleList = () => {
tableRef.current.getList({value:'我是一个参数123'});
}
return (
<div>
<Children ref={ChildrenRef} />
<button onClick={handleList}>调用子组件的方法</button>
</div>
)
|