将挂钩传递给孩子打字稿的问题

pet*_*gan 2 javascript typescript ecmascript-6 reactjs

我有一个使用钩子的反应组件。我的父组件如下所示:

const Parent = () => {

   const [isActive, setIsActive] = useState(false);

   return (
     <Child isActive={isActive} setIsActive={setIsActive} />
   );
}
Run Code Online (Sandbox Code Playgroud)

这是子组件

type Props = {
   isActive: boolean;
   setIsActive: () => void;
}
const Child = ({ isActive, setIsActive}: Props) {
   // component
} 
Run Code Online (Sandbox Code Playgroud)

我看到的错误是

类型错误:不能将类型'Dispatch <SetStateAction>'分配给>类型'()=> void'。TS2322

Jac*_*pie 5

Props输入的类型Child不正确。React类型为setIsActiveas Dispatch,其定义为:

type Dispatch<A> = (value: A) => void;
Run Code Online (Sandbox Code Playgroud)

您缺少value类型中的参数。这应该是正确的(还请注意,它必须是冒号而不是等号):

type Props = {
   isActive: boolean;
   setIsActive: (active: boolean) => void;
}
const Child = ({ isActive, setIsActive}: Props) {
   // component
} 
Run Code Online (Sandbox Code Playgroud)