[英]Forwarded Ref typescript: forwarding react element
代碼:
import React, { useImperativeHandle, useState } from 'react';
const SnackBar = React.forwardRef((_, ref) => {
const [isSnackbarVisible, setisSnackbarVisible] = useState(false);
const show = (text: string) => {
setisSnackbarVisible(true);
};
const hide = () => {
setisSnackbarVisible(false);
};
useImperativeHandle(ref, () => ({ show, hide }));
if (!isSnackbarVisible) return;
return (
<div
style={{ backgroundColor: 'rgba(0, 0, 0, 0.35)' }}
className="absolute z-50 top-0 bottom-0 left-0 right-0 flex items-center justify-center"
>
<button
onClick={() => {
hide();
}}
>
dasdas
</button>
</div>
);
});
export default SnackBar;
錯誤:
Argument of type '(_: {}, ref: ForwardedRef<unknown>) => Element | undefined' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, {}>'.
Type 'Element | undefined' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>> | null'.
Type 'undefined' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>> | null'.ts(2345)
這里的類型如何?
當您的 Snackbar 不可見時,您將返回一個與方法簽名不兼容的隱式undefined
。 您可以在發布的錯誤消息的最后一行中找到此提示。
嘗試將這行代碼更改為空元素
if (!isSnackbarVisible) return <></>;
或null
:
if (!isSnackbarVisible) return null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.