![](/img/trans.png)
[英]TypeScript Error in React component on useState declaration and passing props to child component
[英]React, passing state setter (useState) to child component with TypeScript
將 useState setter 函數傳遞給子組件時,我很難弄清楚類型。
我試圖簡化為下面的基本代碼:
父母
function Parent() {
const [name, setName] = useState("Structured")
..
return (
<>
<Child setName={setName}/>
</>
孩子
import { Dispatch, SetStateAction } from "react";
function Child(setName: Dispatch<SetStateAction<string>>){
return (
<>
<Input onChange={
(value)=>{
setName(value: SetStateAction<string>)
console.log(value)
}
</Input>
</>
在父母身上,我收到以下錯誤:
類型“{ setName: Dispatch<SetStateAction>; }”不可分配給類型“IntrinsicAttributes & Dispatch<SetStateAction”屬性“setName”在類型“IntrinsicAttributes & Dispatch<SetStateAction>”上不存在。
關於我得到的孩子:
“string | string[]”類型的參數不可分配給“SetStateAction”類型的參數 類型“string[]”不可分配給“SetStateAction”類型
應該
function Child({ setName } : { setName: Dispatch<SetStateAction<string>>}){
Child
組件接受 props,它是一個對象,而不僅僅是setName
值
如果你想要一個完整的 React 組件,你可以在 React 的FC
的幫助下鍵入你的 React 功能組件。 如果不是,例如你不能訪問children
表單props
,因為它不被稱為 React 組件。
對於
onChange
部分,我現在正在做演員,因為我不知道這個Input
的樣子。 你能展示一下嗎?
import { Dispatch, SetStateAction, FC} from "react";
interface ChildPropsType {
setName: Dispatch<SetStateAction<string>>
}
/*
I'm using an interface for convenience, you can
replace it with { setName: Dispatch<SetStateAction<string>> }
*/
const Child : FC<ChildPropsType> = ({setName}) => {
return (
<>
<Input onChange={
(value as string)=>{
setName(value);
}
</Input>
</>
)
}
export default Child;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.