【问题标题】:Conditional output in dropdown component下拉组件中的条件输出
【发布时间】:2022-01-28 17:33:14
【问题描述】:

我想建立一个下拉菜单,显示教授某些乐器的老师(见下图)

下拉组件是这样的:

import * as React from 'react'
import { useState, useEffect } from "react"
import { useStaticQuery, graphql } from 'gatsby'
import { BiChevronDown } from "react-icons/bi";

import StaffList from "./StaffList"


const rows = [
    {
    id: 1,
    title: "Verantwortliche",
    },
    {
    id: 2,  
    title: "Lehrende der Streichinstrumente",
    instrument: "streichinstrumente"
    },
    {
    id: 3,  
    title: "Lehrende der Zupfinstrumente",
    },
    {
    id: 4,  
    title: "Lehrende des Tasteninstruments",
    },
    {
    id: 5,  
    title: "Lehrende des Gesangs",
    },
    {
    id: 6,  
    title: "Lehrende des Schlagzeugs",
    },
    {
    id: 7,  
    title: "Lehrende des Akkordeons",
    },
    {
    id: 8,  
    title: "Lehrende der Musiktheorie",
    },
    {
    id: 9,  
    title: "Lehrende der Früherziehung",
    }
]


class DropDownRows extends React.Component {
    constructor(props) {
    super(props);
    this.state = {isToggleOn: false};
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
    this.setState(prevState => ({
        isToggleOn: !prevState.isToggleOn
    }));
    }
    
    render() {
    return (
        <div className="dropdown-rows">
        {rows.map(row => (
            <div key={row.id}>
            <div className="row">
                <div className="col">{row.title}</div>
                <div className="col">
                <BiChevronDown
                    onClick={this.handleClick}
                    style={{float: "right"}}/>
                </div>
                <div>
                </div>
            </div>
            {this.state.isToggleOn ? <StaffList /> : ''}
            </div>
        ))}
        </div>
    )
    }
}

export default DropDownRows

它使用了这个 StaffList 组件:

import * as React from 'react'
import { StaticQuery, graphql } from 'gatsby'
import { GatsbyImage, getImage } from "gatsby-plugin-image"
import { MDXProvider } from "@mdx-js/react"


function StaffList({ data }) {
    return(
    <StaticQuery
    query={graphql`
        query staffQuery {
        allMdx {
            edges {
            node {
                excerpt(pruneLength: 900)
                id
                body
                frontmatter {
                title
                description
                featuredImage {
                    childImageSharp {
                    gatsbyImageData(
                        placeholder: BLURRED
                    )
                    }
                }
                }
            }
            }
        }
        }       
        `}

        render={data => (
        <div className="staff-container">
        {data.allMdx.edges.map(edge => (
        <article>
            <div className="staff-image-container">
            <GatsbyImage key={edge.node.id} alt='some alt text' image={getImage(edge.node.frontmatter.featuredImage)} style={{margin: "0 auto", padding: "0"}} />
            </div>
            <div style={{margin: "0 2em"}}>
            <div>
                <h4 key={edge.node.id} style={{margin: "0"}}>{edge.node.frontmatter.title}</h4>
                <h5>{edge.node.frontmatter.description}</h5>
            </div>
            <p><MDXProvider>{edge.node.excerpt}</MDXProvider></p>
            </div>
        </article> 
        ))}
        </div>
    )}
    />
    )
}



export default StaffList

这是我从中获取数据的 .mdx 文件之一:

---
title: Diana Abouem à Tchoyi
featuredImage: Foto_07.jpg
description: Violine, Streicherklassen
---

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

现在组件看起来像这样:

我将如何有条件地呈现每个栏的内容。因此,并非所有栏都以相同的内容打开,而只是单击的那一个栏只显示了那些属于所选类别的教师。我的想法是有某种条件语句,将选定的栏标题与教师降价文件中的一个字段进行比较?喜欢

title: Hanna
category: Streichinstrumente

然后if (allMdx.edges.node.frontmatter.category === rows.title) {...}

这就是我所能想到的。也许有人可以帮忙?提前谢谢你。

【问题讨论】:

    标签: javascript reactjs graphql


    【解决方案1】:

    我会有一组存储教师数据的对象。下面的例子。

    const teacherData = [
      { id: 'piano',
        name: "Alex",
        otherData: ...
      },
      ... (similarly for the rest)
    ]

    然后是乐器教师的另一个对象/记录数组。如:

    const records = [
      {
      id: 'piano',
      teacher: []
      }
    ]

    在此之后,我将遍历teacherData 数组中的每个元素以获得最终的记录数组,其中id 是乐器的类型,教师是演奏该类型乐器的所有教师。

    现在,进入显示部分。我会写我的组件如下:

    const Dashboard = () => {
      const [show, setShow] = React.useState([])
      
      function handleClick(id) {
        if show.includes(id) {
          const newShow = show.filter(a => a !== id)
          setShow(newShow)
        } else {
          const newShow = show.push(id)
          setShow(newShow)
        }    
      }
      return (
      <div className="dashboard">
        {records.map((record) => 
          (
          <div className="instrument-wrapper">
          <p onClick={() => handleClick(record.id)} >{record.id}</p> //The name of the instrument
          {show.includes(record.id) ?  (
            <div> 
            ... all the teachers here by mapping through the record.teachers
            </div>
          ) : (null)}
          <div>
          )
        )}
      </div>
      )
    }

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多