我有如下文件夹结构。
src/
components/
Icon/
Icon.js
Style.js
images/
apple.svg
google.svg
facebook.svg
index.js
我想在'images / index.js'中的图像文件夹下导出图像路径。
我在下面尝试过这样的事情。
export const apple = './apple.svg';
export { google } from './google.svg';
export const facebook = './facebook.svg';
我想在'/Components/Icon/Style.js'中加载这些图像的路径,如下所示。
import styled from 'styled-components';
// I know this works fine
import apple from '../../images/apple.svg';
// This doesn't work although I want it to work.
import { google } from '../../images/index';
// This doesn't work as well although I want it to work.
import { facebook } from '../../images/index';
const Icon = styled.i`
background: blah blah blah
`;
export default Icon;
但是,我无法加载图像路径。
这样做的正确方法是什么?
这不可能吗?
export const apple = './apple.svg';
这是我加载图片路径的唯一方法吗?
答案 0 :(得分:1)
import apple from './apple.svg';
import google from './google.svg';
import facebook from './facebook.svg';
export {
apple,
google,
facebook
}
import styled from 'styled-components';
import { apple, google, facebook } from '../../images';
const Icon = styled.i`
background: blah blah blah
`;
export default Icon;
为您的服务器请求每个“图标”的图像感觉非常昂贵。 相反,由于您可以访问我将使用此结构的资源:
src/
components/
Icon/
Apple.js
Google.js
Facebook.js
import React from 'react';
function Facebook({ width = '266', height = '266' } = {}) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={width} height={height} viewBox="0 0 266.893 266.895" enableBackground="new 0 0 266.893 266.895">
<path
fill="#3C5A99"
d="M248.082,262.307c7.854,0,14.223-6.369,14.223-14.225V18.812 c0-7.857-6.368-14.224-14.223-14.224H18.812c-7.857,0-14.224,6.367-14.224,14.224v229.27c0,7.855,6.366,14.225,14.224,14.225 H248.082z"
/>
<path
fill="#FFFFFF"
d="M182.409,262.307v-99.803h33.499l5.016-38.895h-38.515V98.777c0-11.261,3.127-18.935,19.275-18.935 l20.596-0.009V45.045c-3.562-0.474-15.788-1.533-30.012-1.533c-29.695,0-50.025,18.126-50.025,51.413v28.684h-33.585v38.895h33.585 v99.803H182.409z"
/>
</svg>
);
}
export default Facebook;
优点: