我试图将图像作为道具从我的Matchups对象传递到TeamGrid组件。
Home.js
import React from "react";
import TeamGrid from "./TeamGrid.js";
import Prediction from "./Prediction.js";
import GridContainer from "./GridContainer.js";
//Matchups
import Matchups from "./Matchups.js";
export default function TeamSection() {
return (
<div>
<GridContainer>
<TeamGrid logo={Matchups[0].homeImg} alt={Matchups[0].homeAlt} />
<Prediction />
<TeamGrid logo={Matchups[0].awayImg} alt={Matchups[0].awayAlt} />
</GridContainer>
</div>
);
}
TeamGrid.js
export default function TeamGrid(props) {
const classes = useStyles();
const imageClasses = classNames(
classes.imgRaised,
classes.imgRoundedCircle,
classes.imgFluid
);
return (
<GridItem xs={12} sm={12} md={4}>
<Button color="primary">
<Card plain>
<GridItem xs={12} sm={12} md={6} className={classes.itemGrid}>
<img
src={require("../../assets/teams/${this.props.logo}")}
alt={this.prop.alt}
className={imageClasses}
/>
</GridItem>
<h4 className={classes.cardTitle}>
Team
<br />
<small className={classes.smallTitle}>Record</small>
</h4>
</Card>
</Button>
</GridItem>
);
}
Matchups.js
export const Matchups = [
{
homeImg: "Seahawks.gif",
homeAlt: "Seahawks",
awayImg: "Vikings.gif",
awayAlt: "Vikings"
},
{
homeImg: "Titans.gif",
homeAlt: "Titans",
awayImg: "Jaguars.gif",
awayAlt: "Jaguars"
}
];
我当前正在获取:“ TypeError:无法读取未定义的属性'0'”
我在进行这个项目时正在学习React,所以任何帮助将不胜感激!
答案 0 :(得分:1)
您可以这样尝试吗?
import React from "react";
import TeamGrid from "./TeamGrid.js";
import Prediction from "./Prediction.js";
import GridContainer from "./GridContainer.js";
//Matchups
import {Matchups} from "./Matchups.js";
export default function TeamSection() {
return (
<div>
<GridContainer>
<TeamGrid logo={Matchups[0].homeImg} alt={Matchups[0].homeAlt} />
<Prediction />
<TeamGrid logo={Matchups[0].awayImg} alt={Matchups[0].awayAlt} />
</GridContainer>
</div>
);
}
我认为您的问题是您的常数没有作为给定文件的默认对象导出。因此,您有多种解决方案:
import {Matchups} from "./Matchups.js";
...
<TeamGrid logo={matchup.Matchups[0].homeImg} alt={matchup.Matchups[0].homeAlt} />```