[英]Passing a function as a prop to a Typescript React Functional Component
[英]Passing a function as a prop with different parameter types in React with Typescript
我正在嘗試通過 function 更新 React 中的 state,但是 VSCode 警告我輸入問題。 錯誤是Type '(value: string) => void' is not assignable to type '(value: string | number) => void'. Types of parameters 'value' and 'value' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.
Type '(value: string) => void' is not assignable to type '(value: string | number) => void'. Types of parameters 'value' and 'value' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.
或Type '(value: number) => void' is not assignable to type '(value: string | number) => void'. Types of parameters 'value' and 'value' are incompatible. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.
Type '(value: number) => void' is not assignable to type '(value: string | number) => void'. Types of parameters 'value' and 'value' are incompatible. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.
這是在這個代碼塊中:
<DropDownSelect
options={blogTags}
selectedOption={selectedBlogTag}
allPosition="top"
updateFunc={updateSelectedBlogTag}
/>
<DropDownSelect
options={["5", "10", "20", "50"]}
selectedOption={selectedArticleCount}
hideAll={true}
updateFunc={updateArticleCount}
/>
DropDownSelect 有如下接口:
interface IDropDownSelect {
options: string[];
selectedOption: string | number;
hideAll?: boolean;
allPosition?: "top" | "bottom";
updateFunc: (value: string | number) => void;
}
我有以下上下文:
export interface IBlogListContextData {
blogList: IBlogListData[];
blogListPage: number;
setBlogListPage: (page: number) => void;
updateBlogListPage: (page: number) => void;
isLoading: boolean;
fetchBlogList: (page?: number) => void;
blogTags: string[];
selectedBlogTag: string;
selectedArticleCount: number;
updateArticleCount: (value: number) => void;
updateSelectedBlogTag: (value: string) => void;
}
export const blogListContextDefaultValue: IBlogListContextData = {
blogList: [blogListDefault],
blogListPage: 1,
setBlogListPage: () => null,
updateBlogListPage: (page: number) => null,
isLoading: false,
fetchBlogList: () => null,
blogTags: [],
selectedBlogTag: "all",
selectedArticleCount: 5,
updateArticleCount: (value: number) => null,
updateSelectedBlogTag: (value: string) => null,
};
有沒有辦法可以將updateFunc
傳遞給帶有字符串或數字類型的 updateFunc? 我試圖避免使用any
也許您可以重用 updateFunc 類型。
updateSelectedBlogTag: IDropDownSelect['updateFunc']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.