[英]Getting toogleShow is not function when passing as props in react typescript functional component
每當我在反應 typescript 功能組件中作為道具從子組件傳遞到父組件時,我都會收到這樣的錯誤消息 toogleShow is not function 。 在孩子中,我也聲明了一個接口,但仍然出現該錯誤。 我不習慣使用 typescript 進行反應,但我正在學習使用 typescript 進行反應。
應用程序.tsx
import React, { useEffect, useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import { useGetRecipesMutation } from "./services/recipeApi";
import Card from "./component/Card";
function App() {
const [query, setQuery] = useState("");
const [health, setHealth] = useState("vegan");
const [modal, setModal] = useState(false);
const [recipe, setRecipe] = useState({});
const [getRecipes, { data, isLoading }] = useGetRecipesMutation();
useEffect(() => {
getFoodRecipes();
}, [query, health]);
const getFoodRecipes = async () => {
await getRecipes({ query, health });
};
const toggleShow = (recipe: any) => {
setModal(!modal);
setRecipe(recipe);
};
const showModal = (recipe: any) => {
if (modal) {
return (
<>
<MDBModal show={modal} setShow={modal}>
<MDBModalDialog>
<MDBModalContent>
{recipe.label}
</MDBModalContent>
</MDBModalDialog>
</MDBModal>
</>
);
}
};
return (
<>
<div className="App">
<MDBRow className="row-cols-1 row-cols-md-3 g-4">
{data?.hits?.map((item: any) => (
<Card toggleShow={toggleShow} recipe={item.recipe} />
))}
</MDBRow>
{modal && showModal(recipe)}
</div>
</>
);
}
export default App;
卡片.tsx
import React from "react";
import {
MDBCol,
MDBCardGroup,
MDBCard,
MDBCardImage,
MDBCardBody,
MDBCardTitle,
} from "mdb-react-ui-kit";
interface PropsFunction {
toggleShow: (item: any) => void;
}
const Card = (recipe: any, { toggleShow }: PropsFunction) => {
const { recipe: item } = recipe;
return (
<>
<MDBCol>
<MDBCardGroup>
<MDBCard className="h-100 mt-2 d-sm-flex">
<MDBCardImage
src={item.image}
alt={item.label}
position="top"
style={{ cursor: "pointer" }}
onClick={() => toggleShow(item)}
/>
<MDBCardBody>
<MDBCardTitle>{item.label}</MDBCardTitle>
</MDBCardBody>
</MDBCard>
</MDBCardGroup>
</MDBCol>
</>
);
};
export default Card;
嘗試像這樣聲明您的Card
組件:
const Card: React.FC<PropsFunction> = ({recipe, toggleShow}) => {
並將您的界面更改為:
interface PropsFunction {
toggleShow: (item: any) => void;
recipe: any;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.