反应挂钩-导出的方法返回为布尔值

时间:2020-05-13 14:37:32

标签: javascript reactjs typescript react-hooks

我有一个简单的自定义钩子,具有一些切换功能:

mask = energy['Energy Supply'].str.contains('...') == True
energy['Energy Supply'] = energy['Energy Supply'].mask(mask)

# equivalently
# energy.loc[mask, 'Energy Supply'] = np.nan

,我尝试在某些组件中重用它:

import { useState } from 'react';

function useDialog(initialState: boolean) {
    const [isOpen, toggleDialog] = useState<boolean>(initialState);

    const open = () => {
        toggleDialog(true);
    };

    const close = () => {
        toggleDialog(false);
    };

    return [isOpen, open, close];
}

export default useDialog;

为什么onClick发生错误? const SomeDialog = (props: any) => { const [isOpen, open, close] = useDialog(false); console.log('open :>> ', typeof open); // here is function type return ( <div> <button onClick={open}>open</button> // ERRROR! -> Type 'false' is not assignable </div> ); }; export { SomeDialog }; 以及如何正确解决?

2 个答案:

答案 0 :(得分:1)

尝试键入函数而不是值。

type Hook = (initialState: boolean) => [boolean, () => void, () => void];

const useDialog: Hook = initialState => {...}

没有它,open的类型为boolean | (() => void),与类型onClick的{​​{1}}不兼容。

Edit affectionate-gauss-vmef0

答案 1 :(得分:1)

您需要像这样将键入添加到您的自定义钩子中

function useDialog(initialState: boolean):[boolean,() => void,() => void] {
    const [isOpen, toggleDialog] = useState<boolean>(initialState);

    const open = () => {
        toggleDialog(true);
    };

    const close = () => {
        toggleDialog(false);
    };

   return [isOpen, open, close];
}