简体   繁体   English

如何在 Gatsby.map function 中只显示一个元素?

[英]How to show only one element in a Gatsby .map function?

I am new to Gatsby.我是盖茨比的新手。 I have lost with what to do here... please help me...... I want to show only one element(h4) when I click a button.我已经迷失了在这里做什么......请帮助我......当我点击一个按钮时,我只想显示一个元素(h4)。 For example, I have 5 plans and each plan has one button and one h4 tag.例如,我有 5 个计划,每个计划都有一个按钮和一个 h4 标签。 When I click the third button, only the third h4 tag will shows.当我单击第三个按钮时,只会显示第三个 h4 标签。 As expected by my code, when the button is clicked it displays every element's h4 tag of the map.正如我的代码所预期的那样,当单击该按钮时,它会显示 map 的每个元素的 h4 标记。 Is there any way I could active/inactive the component for just one element of the map in this case?在这种情况下,有什么方法可以激活/停用 map 的一个元素的组件? Thank you in advance.先感谢您。

  import React, { useState } from "react"

  const TourPage = ({
      const [isOpen, setOpen] = React.useState(false)
      const toggleOpen = () => {
        setOpen(!isOpen)
      }

  return (
        <article>
           {plans.map((plan, index) => {
              return (
                <div key={index}>
                    <button
                      className="btn"
                      onClick={toggleOpen}
                    > button </button>
                    <div
                      className={`${isOpen ? "active" : "inactive"}`}
                    >
                      <h4>{plan.iternary}</h4>
                    </div>
                 </div>
               )
            })}
        </article>

You need to have multiple states , state for each plan.您需要为每个计划提供多个状态,state。

Here is a simple example, you can achieve it however you like, but the concept is the same: manage multiple states within the component.这是一个简单的例子,你可以随心所欲地实现它,但概念是一样的:管理组件内的多个状态。

const plans = [{ id: `id1`, iternary: "a1" }, { id: `id2`, iternary: "a2" }];

const INITIAL = {
  id1: false,
  id2: false
};

const TourPage = () => {
  const [openManager, setOpenManager] = React.useState(INITIAL);

  return (
    <article>
      {plans.map(plan => {
        const onClick = () => {
          setOpenManager(prev => ({ ...prev, [plan.id]: !prev[plan.id] }));
        };
        return (
          <div key={plan.id}>
            <button className="btn" onClick={onClick}>
              button
            </button>
            <div className={`${openManager[plan.id] ? "active" : "inactive"}`}>
              <h4>{plan.iternary}</h4>
            </div>
          </div>
        );
      })}
    </article>
  );
};

编辑 empty-bush-ks4zw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM