简体   繁体   中英

type useState setter in child component

I am trying to pass a useState setter to a child component, but unsure how to type this.

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

Then in the Child component I am trying to type the setter but I am seeing the following error.

Type 'Dispatch< SetStateAction< string[] > >'is not assignable to type '() => void'.

My code looks like this

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

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

You can specify that the setCount prop function expects a number as first argument and the error will go away.

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
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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