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)
您可以指定setCountprop 函数需要一个数字作为第一个参数,错误就会消失。
type Props = {
count: number;
setCount: (num: number) => void;
}
Run Code Online (Sandbox Code Playgroud)