如何在 Rails/Webpacker/React 应用程序中处理图像? [英] How to handle images in a Rails / Webpacker / React app?
问题描述
我正在使用带有 rails 5.1.4 的 Webpacker 来使用 React、Redux 和 react-router-dom.
I am using Webpacker with rails 5.1.4 to play with React, Redux, and react-router-dom.
我在 app/javascript/src/components/
中有一个 Navbar.jsx
组件需要显示图像,但我无法访问我存储的图像在 app/assets/images/
.
I have a Navbar.jsx
component in app/javascript/src/components/
that needs to display an image, but I am not able to access my images stored in app/assets/images/
.
这是我尝试过的:
<img src="logo.png" alt="Logo" />
<img src="assets/logo.png" alt="Logo" />
<img src="assets/images/logo.png" alt="Logo" />
从根路径开始,最后一次尝试有效,因为 /assets/images/logo.png
确实存在,但是当我导航到 /posts/:id
时,它给了我以下错误:
From root path the last attempt works because /assets/images/logo.png
does exist, but when I navigate to /posts/:id
, it gives me the following error:
logo.png:1 GET http://localhost:3000/posts/assets/images/logo.png 404 (Not Found)
你能帮我吗?以及更多关于在那种或混合 React/Rails 应用程序中处理图像的方式?
Can you help me? And more over what's your way to handle images in that kind or hybrid React/Rails app?
谢谢
推荐答案
只需编辑文件 config/webpacker.yml
并替换这一行:
Just edit the file config/webpacker.yml
and replace this line:
resolved_paths: []
这个:
resolved_paths: ['app/assets']
然后,将图像放入app/assets/images
文件夹并像这样加载:
Then, put the image in app/assets/images
folder and load it like this:
import React from 'react'
import MyImage from 'images/my_image.svg'
const MyComponent = props => <img src={MyImage} />
export default MyComponent
这篇关于如何在 Rails/Webpacker/React 应用程序中处理图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!