hooks中父组件 调用子组件 方法或者数据
2021-12-22 本文已影响0人
家有饿犬和聋猫
useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值
父组件
import React, { useEffect, useState, useReducer, useRef } from 'react';
// 存放子组件的函数
const indexRef = useRef(null);
const EventList = ({ location: { search }}) => {
useEffect(() => {
let params = inputData;
if (isNotEmpty(search)) {
let str = search?.split('?')[1];
let queryObj = queryString.parse(str, '&', '=');
queryObj = queryString.parse(Object.keys(queryObj)[0]);
if (queryObj?.time === 'custom') {
// 调用子组件hooks函数
indexRef.current.setUseCustomDate(true);
}
}
getData(params);
}, []);
return (
<div>
<Path list={paths} />
<div className={styles.topTip}>
<span>{title}</span>
</div>
<FilterList
// 获取子组件的ref
onRef={(ref) => (indexRef.current = ref)}
/>
</div>
);
};
export default withRouter(EventList);
子组件
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react';
const FilterList = ({
onRef,
location: { search },
...rest
}) => {
const [dropDownVisible, setDropDownVisible] = useState(false);
const [useCustomDate, setUseCustomDate] = useState(null);
// 通过 useImperativeHandle 将子组件的实例属性输出到父组件
useImperativeHandle(onRef, () => ({
setDropDownVisible: setDropDownVisible,
setUseCustomDate: setUseCustomDate
}));
return (
<div> 1233 </div>
);
}
export default FilterList;