我正在我的应用程序中构建自定义模态组件。但是在Ts类型检查时出现此错误。这是我的代码:
Modal.tsx
import React, {useEffect, useRef} from 'react';
import {createPortal} from 'react-dom';
import {useOnClickOutside} from "../hooks";
interface Props {
isOpen: boolean;
toggle: (isOpen: boolean) => void;
title: string;
width?: any;
}
const modalRoot = document.getElementById('modal');
const Modal: React.FC<Props> = ({isOpen, toggle, title, width = 700, children}) => {
const ref = useRef<HTMLDivElement>(null);
const el = document.createElement('div');
useOnClickOutside(ref, () => toggle(false));
useEffect(() => {
if (modalRoot) modalRoot.appendChild(el);
return (() => {
if (modalRoot) modalRoot.removeChild(el);
})
});
return (
isOpen ? createPortal(
<React.Fragment>
{children}
</React.Fragment>, el
) : null
)
};
export default Modal;
useModal.tsx
const useModal = () => {
const [isOpen, setIsShowing] = useState<boolean>(false);
const toggle = (isOpen: boolean) => {
setIsShowing(isOpen);
};
return [
isOpen,
toggle,
]
};
export default useModal;
使用
const [isOpen, toggle] = useModal();
return (
<Modal title={'Enter link URL'}
isOpen={isOpen} toggle={toggle}> //this line I get error
<div>....</div>
</Modal>
)
我不知道为什么。请帮助我
答案 0 :(得分:1)
看来打字稿正在推断useModal
函数的返回类型为(boolean | ((isOpen: boolean) => void))[]
。尝试将其第一个元素分配给isOpen
时,这会引起问题,因为它期望一个布尔值,但您却给它一个boolean | ((isOpen: boolean) => void)
。
您实际想要的返回类型为[boolean, (isOpen: boolean) => void]
,因此请尝试明确指出:
const useModal = () : [boolean, (isOpen: boolean) => void] => {
const isOpen = true;
const toggle = (isOpen: boolean) => {
//setIsShowing(isOpen);
};
return [
isOpen,
toggle,
]
};
export default useModal;