[英]How to fix error argument of type undefined is not assignable to parameter of type 'string or () => string usng typescript and react?
[英]How to fix the error argument of type string or undefined is not assignable to parameter of type string using typescript and react?
我收到字符串类型的错误参数或未定义的参数不能分配给使用 typescript 的字符串类型参数并做出反应
下面是我的代码,
function List({items}: Props) {
const [activeindex, setActiveindex] = React.useState<string>();
return (
items.map((item: any) => {
<AddButton setActiveIndex={setActiveIndex} itemId={item.id}/>
}
);
}
interface AddButtonProps {
setActiveIndex: any;
itemId?: string;
}
function AddButton ({setActiveIndex, itemId}: AddButtonProps){
const {toggleDrawing} = useDrawing();
const handleClick = (itemId) => {
setActiveIndex(itemId);
toggleDrawing(itemId); //error here
}
return (
<Button onClick={handleClick}/>
);
);
function useDrawing () {
const [editableItemId, setEditableItemId] = React.useState<string>();
const toggleDrawing = React.useCallback(async (itemId: string) => {
if (isDrawing && editableItemId === itemId) {
cancelDrawing();
} else if (isDrawing) {
cancelDrawing();
setEditableItemId(itemId);
} else {
setEditableWorkAreaId(itemId);
}
},
[isDrawingPolygon, editableItemId, cancelDrawing]
);
}
我不确定为什么会收到此错误。 有人可以帮我解决这个问题。 谢谢。
试试这个方法;)
const toggleDrawing = React.useCallback(async (itemId: string | undefined) => {
if (isDrawing && editableItemId === itemId) {
cancelDrawing();
} else if (isDrawing) {
cancelDrawing();
setEditableItemId(itemId);
} else {
setEditableWorkAreaId(itemId);
}
},[])
你的接口定义了itemId?: string;
和一个字符串或未定义,但 function 调用需要一个字符串。
使用任一
if (itemId) {
toggleDrawing(itemId);
}
或者
toggleDrawing(itemId || '');
或者
toggleDrawing(itemId as string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.