繁体   English   中英

在子组件中输入 useState setter

[英]type useState setter in child component

我正在尝试将useState设置器传递给子组件,但不确定如何输入。

const Parent = () => {
   const [count, setCount] = useState(0);
   return(
     Child count={count} setCount={setCount} />
   );
}

然后在Child组件中,我尝试输入设置器,但我看到以下错误。

类型 'Dispatch< SetStateAction< string[] > >' 不可分配给类型 '() => void'。

我的代码看起来像这样

type Props = {
  count: number;
  // the issue is the line below
  setCount: () => void;
}

const Child = ({ count, setCount }: Props) => {
    .... code here
}

您可以指定setCount prop 函数需要一个数字作为第一个参数,错误就会消失。

type Props = {
  count: number;
  setCount: (num: number) => void;
}
const Parent = () => {
   const [myState, setMyState] = useState<YourType>({});
   return(
     Child myState={myState} setMyState={setMyState} />
   );
}
import { Dispatch, SetStateAction } from 'react'

type Props = {
  count: AnyType;
  setCount: Dispatch<SetStateAction<YourType>>;
}

const Child = ({ myState, setMyState }: Props) => {
  // works with
  setMyState(newState)

  // also with
  setMyState(oldState => {
    // ...
    return newState
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM