在子组件中输入 useState setter

pet*_*gan 3 javascript types typescript ecmascript-6 reactjs

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

const Parent = () => {
   const [count, setCount] = useState(0);
   return(
     Child count={count} setCount={setCount} />
   );
}
Run Code Online (Sandbox Code Playgroud)

然后在Child组件中,我尝试键入 setter,但我看到以下错误。

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

我的代码看起来像这样

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

const Child = ({ count, setCount }: Props) => {
    .... code here
}
Run Code Online (Sandbox Code Playgroud)

Fil*_*ima 11

const Parent = () => {
   const [myState, setMyState] = useState<YourType>({});
   return(
     <Child count={myState} setCount={setMyState} />
   );
}
Run Code Online (Sandbox Code Playgroud)
import { Dispatch, SetStateAction } from 'react'

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

const Child = ({ count, setCount }: Props) => {
  // works with
  setCount(newState)

  // also with
  setCount(oldState => {
    // ...
    return newState
  })
}
Run Code Online (Sandbox Code Playgroud)


Tho*_*lle 7

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

type Props = {
  count: number;
  setCount: (num: number) => void;
}
Run Code Online (Sandbox Code Playgroud)

  • 我很想知道如何像 React 那样输入它。因为您不能只将数字传递给原始设置器,所以您还可以传递一个函数来使用先前的状态修改状态 (4认同)