react typescipt hook 实现父组件调用子组件(
2022-02-11 本文已影响0人
_嘿嘿_
子组件
export interface MychildRef {
childClick: () => void;
}
const Test = (props: {}, ref: React.Ref<MychildRef>) => {
const {
data: userInfo,
loading,
run,
} = useRequest(getUserInfo, {
manual: true,
});
useImperativeHandle(ref, () => ({
childClick: () => {
clickHandle();
},
}));
const [flag, { toggle }] = useBoolean(true);
const clickHandle = () => {
let text = flag ? "大可" : "小涛";
run(text);
toggle();
};
return (
<>
<button onClick={clickHandle}>点击</button>
{loading ? <div>loading...</div> : <div>Username: {userInfo?.name}</div>}
</>
);
};
export default forwardRef(Test);
父组件调用
function App() {
const inputEl = useRef<MychildRef>(null);
const clickChildHandle = () => {
inputEl.current?.childClick();
};
return (
<div className="App">
<button onClick={clickChildHandle}>点击儿子节点</button>
<Test1 ref={inputEl}></Test1>
</div>
);
}