Select 在反应中的活动图像之间

Select between active images in react

我目前正在尝试让 Gatsby 通过单击切换产品页面上的主图像。我看到很多使用状态并通过状态操作切换活动 class 的解决方案,但由于某种原因,我无法将状态或任何其他功能添加到我当前的 js 文件中。我正在使用 Gatsby 和 Gatsby Images 来渲染图像。

我现在的样子I want to be able to select between these three images and make the selected image the big main one

这是我的代码,我知道它很乱,但一直在摆弄它,试图让它工作

const Product = ({ data }) => {
    const post = data.shopifyProduct;


    return (
        <Layout>
            <h1>{post.title}</h1>
            <h5>Price: <span>{post.variants[0].price}</span></h5>
            <div
              dangerouslySetInnerHTML={{ __html: post.description }}
            />
            <GatsbyImage id="main" image={getImage(post.images[0])} alt={post.images.altText} />
              <div class="gallery">
                <GatsbyImage id="img-2" image={getImage(post.images[0])} alt={post.images.altText} />
                <GatsbyImage id="img-2" image={getImage(post.images[1])} alt={post.images.altText} />
                <GatsbyImage id="img-2" image={getImage(post.images[2])} alt={post.images.altText} />
              </div>
        </Layout>
    );
  };


Product.propTypes = {
    data: PropTypes.object.isRequired,
};

感谢查看

您应该能够使用 React useState 挂钩 (https://reactjs.org/docs/hooks-state.html):

// If you haven't already:
// import * as React from 'react'

const Product = ({ data }) => {
    const post = data.shopifyProduct;
    const [imgIndex, setImgIndex] = React.useState(0 /* or your default */)

    return (
        <Layout>
            <h1>{post.title}</h1>
            <h5>Price: <span>{post.variants[0].price}</span></h5>
            <div
              dangerouslySetInnerHTML={{ __html: post.description }}
            />
            <GatsbyImage id="main" image={getImage(post.images[imgIndex])} alt={post.images.altText} />
              <div class="gallery">
                <GatsbyImage onClick={() => { setImgIndex(0) }} id="img-2" image={getImage(post.images[0])} alt={post.images.altText} />
                <GatsbyImage  onClick={() => { setImgIndex(1) }} id="img-2" image={getImage(post.images[1])} alt={post.images.altText} />
                <GatsbyImage  onclick={() => { setImgIndex(2) }} id="img-2" image={getImage(post.images[2])} alt={post.images.altText} />
              </div>
        </Layout>
    );
  };


Product.propTypes = {
    data: PropTypes.object.isRequired,
};