Saya mencoba menampilkan gambar dari file services.js dan gambar dari src di bawah folder assets dan saya ingin menyimpan gambar di services.js dari assets tetapi ketika saya memberikan path file itu tidak menampilkan gambar. Ini kode saya: cara memberi nama jalur file di js yang ada di folder berbeda. Jalur relatif gambar saya adalah src\assets\Mover.jpg. dan jalur relatif service.js saya adalah src\Services.js

import React from "react";
import "./Services.css";

export default class Services extends React.Component {
  constructor(props) {
    super(props);

    const Services = [
      {
        id: 0,
        Mover_src: "./assets/Mover.jpg",
        title: "Plumbing Services",
        overview: "hello this is plumbing service"
      },
     {id:1,
      Mover_src: "./assets/plumb.jpg",
      title:"Moving Services", 
      overview:"hello this is plumbing service"}

    ];

    var serviceRows = [];
    Services.forEach(service => {
      console.log(service.title);
      const serviceRow = (
        <table key={service.id}>
          <tbody>
            <tr>
              <td>
                <img alt="Mover" width="300" src={service.Mover_src} />
              </td>
              <td>{service.title}</td>
            </tr>
          </tbody>
        </table>
      );
      serviceRows.push(serviceRow);
    });
  this.state = { rows: serviceRows };
 }
 render(){
   return(
     <div className="main">
      {this.state.rows}
     </div>
   );
 }
}
2
Hatpe123 6 Maret 2020, 21:57

1 menjawab

Jawaban Terbaik

Perubahan:

const Services = [
      {
        id: 0,
        Mover_src: "./assets/Mover.jpg",
        title: "Plumbing Services",
        overview: "hello this is plumbing service"
      },
     {id:1,
      Mover_src: "./assets/plumb.jpg",
      title:"Moving Services", 
      overview:"hello this is plumbing service"}

    ];

Untuk:

const Services = [
      {
        id: 0,
        Mover_src: require("./assets/Mover.jpg"),
        title: "Plumbing Services",
        overview: "hello this is plumbing service"
      },
     {id:1,
      Mover_src: require("./assets/plumb.jpg"),
      title:"Moving Services", 
      overview:"hello this is plumbing service"}

    ];

Sehingga webpack dapat mengimpornya dengan benar.

1
StackedQ 6 Maret 2020, 19:33