![](/img/trans.png)
[英]React, passing state setter (useState) to child component with TypeScript
[英]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.