首页 > 解决方案 > 将图像作为道具传递

问题描述

我正在尝试将图像作为道具从我的 Matchups 对象传递给我的 TeamGrid 组件。

主页.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,所以任何帮助都将不胜感激!

标签: reactjsreact-props

解决方案


你可以试试这样:

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>
  );
}

我认为你的问题是你的常量没有作为给定文件的默认对象导出。所以你有多种解决方案:

  1. 您可以在导入对象时分解对象:import {Matchups} from "./Matchups.js";
  2. 您可以使用导入的对象和访问常量作为对象的属性
    ...
    <TeamGrid logo={matchup.Matchups[0].homeImg} alt={matchup.Matchups[0].homeAlt} />```
    

推荐阅读