如何解决盖茨比:通过道具传递图片
我有一个关于盖茨比的问题,特别是关于如果我使用JS对象的情况下如何导入图像的问题,因为我是通过一个道具传递它的(请看代码列n°1,N°2中的文字对象)第三列是整个组件,所有对象都被调用。
在Gatsby的文档中说,我们需要在组件顶部导入img或SVG,但在这种情况下,我不能这样做。
此外,即使在使用自动完成路径Visual Studio Code扩展时,我也尝试在组件中添加src={require(img)}
,但仍然无法正常工作:
谢谢!
代码:
第一列heroSection.js。我通过一个道具传递图像,因为我需要多次使用该组件,只是没有道具就不能放一张图像:
import React from 'react';
import { Spring } from 'react-spring/renderprops';
import './heroSection.css';
import { Button } from './button';
import { Link } from 'gatsby';
export default function HeroSection({
lightBg,topLine,lightText,lightTextDesc,headline,description,buttonLabel,img,alt,imgStart
}) {
return (
<>
{/* Background Color */}
<div className={lightBg ? 'home__hero-section' : 'home__hero-section darkBg'}>
{/* Container: Row & Column */}
<div className='container'>
<div className='row home__hero-row'
style={{
display: 'flex',flexDirection: imgStart === 'start' ? 'row-reverse' : 'row'
}}
>
{/* Column */}
<div className='col'>
{/* Toplin & Header */}
<div className='home__hero-text-wrapper'>
<Spring from={{ opacity:0 }} to={{ opacity:1 }} config={{ delay: 900,duration: 1100 }} >
{props => (
<div style={props}>
<div className='top-line'>{topLine}</div>
<h1 className={lightText ? 'heading' : 'heading dark'}>
{headline}
</h1>
{/* Description */}
<p className={ lightTextDesc ? 'home__hero-subtitle' : 'home__hero-subtitle dark' }>
{description}
</p>
{/* Button */}
<Link to='/sign-up'>
<Button buttonStyle='btn--ghost' buttonColor='scarlet' buttonSize='btn--wide' >
{buttonLabel}
</Button>
</Link>
</div>
)}
</Spring>
</div>
</div>
{/* Image */}
<div className='col'>
<div className='home__hero-img-wrapper'>
<img src={img} alt={alt} className='home__hero-img' loading="lazy"/>
</div>
</div>
</div>
</div>
</div>
</>
);
}
第2列indexData.js JS对象以及将要传递给组件属性的数据(第1列)。
export const tecnologia = {
lightBg: false,lightText: true,lightTextDesc: true,topLine: 'Tecnología y Ambiente',headline: 'Horticultura urbana tecnológica para todos',description:
'Nuestro sofware te acesora,supervisa y mejora tus cultivos urbanos además de ser altamente soportada por la comunidad por su código abierto.',buttonLabel: '¡Empieza Ahora!',imgStart: 'start',img: '/src/images/environment.svg',alt: 'Environment'
};
export const comunidad = {
lightBg: true,lightText: false,lightTextDesc: false,topLine: 'Amado por la comunidad',headline: 'El software es atendido por la comunidad',description:
"Sin importar el tipo de cultivo,la comunidad aporta semanalmente grandes cambios y variaciones d nustro software modular para hacer más amplio la cartera de plantas que el usuario podrá cultivar sin procuparse.",buttonLabel: 'Abrir Repositorio',imgStart: '',img: '../images/programmer.svg',alt: 'Programmer'
};
export const seguridad = {
lightBg: false,topLine: '100% Seguro',headline: 'Protegemos tus datos',description:
'¡Confía en nosotros! No vendemos tus datos sensibles a terceros,la seguridad y confianza es menester para nuestro producto',buttonLabel: 'Leer Políticas',img: '../images/sec.svg',alt: 'Seguridad'
};
export const estadistica = {
lightBg: false,topLine: 'Ciencia De Datos',headline: 'Ofrecemos estadísticas de tus cosechas para mejorarlas',description:
'Analizamos los datos para ofrecer un mejor servicio y los abrimos anónimamente a la comunidad,para así enfocarnos en una mejor experiencia de usuario,cosechas más fértiles y ahorro de tiempo.',buttonLabel: 'Registrate Ahora',img: '../images/data.svg',alt: 'Data'
};
第3列index.js,也称为Home或IndexPage。这是被多次使用的组件。
import React from "react";
import './index.css';
import Layout from './../components/layout';
import HeroSection from './../components/heroSection';
import { tecnologia,comunidad,seguridad,estadistica } from './indexData.js';
export default function IndexPage() {
return (
<Layout>
<HeroSection {...tecnologia} />
<HeroSection {...comunidad} />
<HeroSection {...seguridad} />
<HeroSection {...estadistica} />
</Layout>
)
}
解决方法
您不需要在顶级组件中导入图像。您可以将其导入到任何位置,并以多种方式使用它。
免责声明:如果您使用的是SVG,我建议您使用following SO answer。
如果您的images are inside the filesystem of Gatsby,可以通过GraphQL进行查询并使用gatsby-image
。
如果没有,只需导入asset directly in your component:
import React from "react"
import logo from "./logo.png" // Tell webpack this JS file uses this image
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
P.S:请提供代码示例而非图片。
解决方案在indexData
内部使用了这样的导入方式:
import a from '../images/a.svg';
const obj = { img: a }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。