【问题标题】:React returns image src as objectReact 将图像 src 作为对象返回
【发布时间】:2018-10-27 18:01:02
【问题描述】:

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

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}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      team[0].image{"foo":"yourUrl"} 形式的对象,因为您已将foo 包裹在方括号中,它使用对象简写语法创建一个名为foo 的属性,其值位于变量foo 中。去掉foobar周围的括号

      【讨论】:

        【解决方案3】:

        就我而言,过去四个小时我都在挣扎。但是,这是一个 Next JS 项目,所以我需要将图像属性放在图像组件中。 &lt;Image src={props.img} /&gt; 而不是 &lt;img&gt;

        【讨论】:

        • 如果您有新问题,请点击 按钮提出问题。如果有助于提供上下文,请包含指向此问题的链接。 - From Review
        猜你喜欢
        • 2016-06-18
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        • 2021-10-04
        • 2021-04-14
        • 1970-01-01
        相关资源
        最近更新 更多