【问题标题】:Gatsby: pass an image through props盖茨比:通过道具传递图像
【发布时间】:2021-02-13 19:44:42
【问题描述】:

我有一个关于 Gatsby 的问题,特别是关于如果我使用 JS 对象时如何导入图像,因为我通过道具传递它(查看代码列 n°1,文字对象 N°2)第三列是整个组件以及所有被调用的对象。

在 Gatsby 的文档中说我们需要在组件顶部导入 img 或 SVG,但在这种情况下,我不能。

另外,我尝试在组件中添加src={require(img)},但仍然无法正常工作,即使我使用了自动完成路径 Visual Studio Code 扩展:

提前致谢!

代码:

第一列 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,
  lightText: true,
  lightTextDesc: true,
  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',
  imgStart: 'start',
  img: '../images/sec.svg',
  alt: 'Seguridad'
};

export const estadistica = {
  lightBg: false,
  lightText: true,
  lightTextDesc: true,
  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',
  imgStart: '',
  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>
  )
}

【问题讨论】:

    标签: reactjs import gatsby react-props gatsby-image


    【解决方案1】:

    您不需要在顶级组件中导入图像。您可以将它导入到任何您想要的地方,并以多种方式使用它。


    免责声明:如果您正在处理 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 }
    

    【讨论】:

    • 感谢您的评论,但我需要将 SVG 作为道具传递,因为我需要多次使用 和不同的 SVG。我一直在尝试链接这个但不起作用``` ``` 在控制台中给我一个错误。我已经把代码放在问题中了。谢谢
    • 您可以传递图像、图像本身、图像路径或 SVG 组件(检查提供的链接)以在子组件中呈现。确保您的图像在向下传递之前显示。
    • 终于!有用!我在 IndexData 的对象中使用了大括号,插入了选择的常规名称:``` import a from '../images/a.svg'; const obj = { img: a } ``` 感谢您的宝贵时间。我有很多东西要学。
    • 很高兴为您提供帮助,我已经用解决方案更新了答案。如果问题已解决,请接受答案以关闭问题。
    猜你喜欢
    • 2020-02-20
    • 2021-07-30
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多