首页 > 解决方案 > 单击时显示/隐藏列表的元素,一次一个列表项(反应应用程序)

问题描述

我正在尝试制作一个列表,当您单击标题时,它会显示/隐藏每个标题下方的描述。它部分工作(当您单击标题时,它会显示所有描述,当您再次单击时,它将全部隐藏),但我需要它来单独显示/隐藏每个项目。

import React from 'react'
import styled from 'styled-components'
import girl from '../assets/steps-image.png'
import arrow from '../assets/down-arrow.svg'

class StepsSection extends React.Component{
  constructor() {
    super();
    this.state = {
      show: true
    }
  }
render() {
  return (
    <StepsStyles  className="sections">
    <Illustration />
     <Content>
       <div><span className="tag">3 easy steps</span></div>
      <h1>How it works</h1>

在这里,我们有清单:

      <ul>
        {Steps.map((lista, i)=>(
        <li key={i}>
        <div key={i} onClick={()=>{this.setState({show:!this.state.show})}} className="dropdown"><h2>{lista.title}</h2><img src={arrow} alt="" /></div>
        { this.state.show? <p>{lista.desc}</p> : null}
    </li>
        ))}
        
      </ul>
     </Content>
  </StepsStyles>
  )
}
}

export default StepsSection

这只是样式化的组件:

const StepsStyles = styled.div`
  background: url(${girl}) no-repeat left;
  background-position: left center;
  background-size: contain;  
  margin-top: 200px;
  text-align: left;
  display: grid;
  height: 50vh;
  grid-template-columns:1fr 1fr;
  /* max-height: 50vh; */
  h1{
    font-weight: bold;
    margin-bottom: 5vh;
  }
`

  const Illustration = styled.div`
  grid: 1;
  `

  const Content = styled.div`
  grid: 2;
  text-align: left;
  img {
    max-width: 10px;
    max-height: 10px;
  }
  h2{
    font-weight: bold;
    font-size: 16px;
  }
  ul{
    width: 60%;
  }
  li {
    margin-bottom: 2vh;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--superlight-gray);
    ::last-child{
      border-bottom: none;
    }
    .dropdown {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 10px;
    }
  }
  ` 

json 静态数据位于底部:

const Steps = [
    {
      title: '1. Download Tattoo master app (dropdown)',
      desc: 'Download the application in App Store and you acan find the wizard in any location around the world. '
    },
    {
      title: '2. Enter your location',
      desc: 'Download the application in App Store and you acan find the wizard in any location around the world.'
    },
    {
      title: '3. Find your tattoo master',
      desc: 'Download the application in App Store and you acan find the wizard in any location around the world.'
    }
  ]

这是页面:https ://mastertattoo-landpage.netlify.app 和回购:https ://github.com/micazev/mastertattoo-landpage

有任何想法吗?提前致谢!

标签: javascriptreactjs

解决方案


你可以使用这样的东西......

{Steps.map((lista, index) => (
  <details className='collapse'>
    <summary className='title'>{lista.title}</summary>
    <div className='description'>
      {lista.desc}
    </div>
  </details>
))}

details 和 summary 是折叠的 HTML 标签。


推荐阅读