将图像作为对象放入状态变量并将其作为道具传递

时间:2019-03-24 15:47:16

标签: javascript reactjs

我试图将图像作为对象放入状态,并通过状态作为道具进行反应,但是它什么也没通过。

import xaprikaScreen from "./images/xaprikaScreenShot.jpg";
import linguadenScreen from "./images/linguadenScreenShot.jpg";

export class Portfolio extends Component {
  constructor() {
    super();
    this.state = {
      currentProject: 0,
      projects: [
        {
          id: 1,
          projectName: "Linguaden.com",
          projectLink: "www.linguaden.com",
          githubLink: "",
          displayPicture: { linguadenScreen },
          projectDescription: ""
        },
        {
          id: 2,
          projectName: "Xaprika.com",
          projectLink: "www.Xaprika.com",
          githubLink: "",
          displayPicture: { xaprikaScreen },
          projectDescription: ""
        }
      ]
    };
  }

render() {
    return (
    <Projects imageSource={this.state.projects[this.state.currentProject["displayPicture"]}/>
);
}
}
}

在这里,我已将2个图像作为对象导入,然后将它们分配为状态,然后尝试将这些变量作为道具传递。

1 个答案:

答案 0 :(得分:1)

这里的问题是您在做this.state.currentProject["displayPicture"]currentProject的值为0,而0.displayPicture未定义。然后,您要做的是this.state.projects[this.state.currentProject["displayPicture"],它不仅没有右括号,即使这样做也等同于this.state.projects[undefined],后者也未定义。

用下面的代码替换渲染函数,它应该可以工作。

render() {
  return (
    <Projects imageSource={this.state.projects[this.state.currentProject].displayPicture} />
  );
}