Reactjs 不渲染本地图像

时间:2021-03-12 00:23:24

标签: javascript reactjs next.js

我正在尝试在我的 next.js 项目中加载图像,但是我使用的是来自 react 的原生图像。 图像未加载到页面中,因此我将在下面链接到我的两个 js 文件(样式和组件)。 希望你能帮我

import {Container, ProfileImage, Text} from './styles'

export default function Profile() {
    return (
        <Container>
            <ProfileImage 
                src="../../../public/images/profile.png"
            />
        </Container>
    )
}
import styled from 'styled-components'

export const Container = styled.div`
    display:flex;
    align-items:center;
    align-items:center;
    flex-direction:column;
`

export const ProfileImage = styled.img`
    border-radius:50%;
    width:300px;
    height:300px;
    border: 1px, black;
`

编辑: 完整代码在:https://github.com/FranciscoJLucca/franciscolucca.github.io

5 个答案:

答案 0 :(得分:1)

我建议将图像作为组件导入,然后在您的函数中调用它。我过去遇到过类似的问题,这解决了我的问题! 示例:

import {yourImage} from "../yourfolder/Image.png"
export default function Profile() {
return (
 <img src={yourImage}></img>
  )

答案 1 :(得分:1)

感谢所有试图提供帮助的人,但我发现了发生了什么。 默认情况下,Next.js 只加载 /public 文件夹内的图像,为了让它识别其他路径,必须添加一个库,next-image,我还必须创建一个配置文件对于 next.js,next.config.js 如下。

const withImages = require ('next-images')
module.exports = withImages ({
    esModule: true,
})

我在 next.js image optimization

中获得此信息

答案 2 :(得分:0)

更新:我查看了存储库,您必须解决两件事:

  1. 修正拼写错误:styled.image -> styled.img
  2. 使用不包括公共目录的绝对路径:src='/images/Profile.png'

旧答案:您可能需要为 webpack 配置加载器。我建议使用 url-loader,这里接受的答案中有一个方便的指南:IMAGE: You may need an appropriate loader to handle this file type

答案 3 :(得分:0)

src 应该是这样的。

                src="/images/profile.png"

只是不要使用确切的路径../../public。 它不会工作。

答案 4 :(得分:0)

请像这样导入您的图像。

import {youjsrImage} from "/sourceDirectory";

然后在渲染函数中使用代码,如:

<img src={yourImage}></img>