React返回图像src作为对象

时间:2018-10-27 18:01:02

标签: reactjs

我有一个这样定义的变量:

const team = [
  {
    name: "Foo",
    bio: "FooBar",
    image: { foo }
  },
  {
    name: "Bar",
    bio: "FooBar",
    image: { bar }
  },
];

图像导入位置如下:

import foo from "../assets/foo.jpg";
import bar from "../assets/bar.jpg";

然后将这些传递给要渲染的组件,

<TeamRow team={team} />

The TeamRow component looks like this:

const TeamRow = props => {
  const items = props.team.map((item, index) => {
    return (
      <div className="col-10 col-sm-4 col-md-1 mx-auto text-center">
        <div className="row">
          <div className="col-12 teamMemberImage">
            <img className="img-fluid" src={item.image} />
          </div>
        </div>
        <div className="row">
          <div className="col-12">{item.name}</div>
        </div>
        <div className="row">
          <div className="col-12">{item.bio}</div>
        </div>
      </div>
    );
  });
  return <div className="row">{items}</div>;
};

export default TeamRow;

图像无法渲染。当我在开发工具中查看它们时,它们具有src="Object object"。调用TeamRow的类是定义team的类。定义后,调用console.log(foo将返回指向图像的URL,这与预期的一样。不知何故,在传递给第二个组件时,预期的行为就停止了。

奇怪的是,早些时候,我使用react徽标作为占位符。所以: import logo from "../assets/logo.svg";,并且可行,但前提是我将其渲染为src={item.image.logo}

2 个答案:

答案 0 :(得分:0)

{ foo }{ foo: foo }的简写,而{ bar }{ bar: bar }的简写。

您可以将图像url直接设置为image属性,而不是将图像url放在每个图像都不同的键的对象中。

const team = [
  {
    name: "Foo",
    bio: "FooBar",
    image: foo
  },
  {
    name: "Bar",
    bio: "FooBar",
    image: bar
  },
];

答案 1 :(得分:0)

team[0].image{"foo":"yourUrl"}形式的对象,因为您已将foo括在方括号中,该括号使用对象的简写语法创建了一个名为foo的属性,并带有变量foo中的值。移除foo和bar周围的括号