为什么图像不显示在 React Typescript 和 Styled Component 上

Why image not displaying on React Typescript and Styled Component

我正在尝试在使用 typescript 模板创建的 React 项目中显示图像。

代码运行后页面仅显示图像图标,不显示图像本身。我做错了什么?

我使用了:create-react app --template typescript。如果我把它放在 public 目录中,我将无法访问它。所以文件夹放在src目录下。

这是组件的样子:

import React from 'react';
import styled from 'styled-components';

const logo = require('../../src/images/logo.png');

const StyledTable = styled.div``;

export const MyPage: React.FC = () => {
  return (
    <StyledTable>
      <img alt="Profile Image" style={{ width: 100 }} src={String(logo)} />
    </StyledTable>
  );
};

export default MyPage;

这是它的样子:

您在使用 Create-React-App 吗?如果是,则有an easier way to import images

从文档中复制

import React from 'react';
import logo from './logo.png'; // Just import it

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;