【发布时间】:2021-11-10 02:05:12
【问题描述】:
我正在尝试根据类型渲染一张带有紫色背景的猫和一张背景为蓝色的卡片,当它是一只狗时。该卡片的设计对每一种动物都是独一无二的。
json 文件
"animals": [
{
"id": 1,
"type": "Cat",
},
{
"id": 2,
"type": "Dog",
}
]
AnimalAdopt.tsx
const AnimalAdopt = ({ animals }) => {
return (
<Card className="list-group">
{animals.map((animals) => (
<DogCard>
<HeaderContainer>
<HeaderCard>
<Image>
<img src={animals.photo} width='120px' height='120px' alt='Picture of a cute dog' />
</Image>
<Name>{animals.name}</Name>
</HeaderCard>
</HeaderContainer>
App.tsx
const url = 'http://localhost:3000/pets';
function App() {
const [animals, setanimals] = useState(null);
useEffect(() => {
axios.get(url).then((result) => {
setanimals(result.data);
});
}, []);
return (
<div>
< Header />
{animals ? <AnimalAdopt animals={animals} /> : < Loading />}
</div>
);
}
export default App;
【问题讨论】:
-
animals.map((animal) => { const Card = animal.type === "Cat" ? CatCard : DogCard; return <Card>...</Card>; });
标签: javascript reactjs json axios jsx