【问题标题】:Show/Hide div in a mapping ReactJS在映射 ReactJS 中显示/隐藏 div
【发布时间】:2020-10-15 09:23:11
【问题描述】:

我目前正在学习 ReactJS,我在尝试隐藏/显示 div 时遇到了问题!以下代码正在运行,但是当我单击“了解更多”按钮时,它会隐藏每张卡片上的所有描述,但我想仅在单击它的位置显示/隐藏描述。

import Axios from 'axios';
import React, { useEffect, useState } from 'react';
import JobApplicationList from './JobApplicationList';
import Card from "react-bootstrap/Card";
import ScriptTag from 'react-script-tag';



export default class Home extends React.Component{
    
    constructor(){
        super()
        this.state={
            showMe:true,
            advLists: []
        }
    }

    operation(){
        this.setState({
            showMe:!this.state.showMe
        })
    }

    
    
      componentDidMount() {
        Axios.get(`http://localhost:3001/get/adv`)
          .then(res => {
            const advLists = res.data;
            
            this.setState({ advLists });
          })
      }

      

render(){
    

    return (
        
        <div className="main-page">
            <div className="adv_container">
                {this.state.advLists.map((val, key) => {
                    return (
                        <div className="card_">
                            <Card style={{ width: "100%" }}>
                                <Card.Body>
                                    <Card.Title>{val.compName}</Card.Title>
                                    <Card.Subtitle className="mb-2 text-muted">
                                    {val.city} | {val.compWebsite}
                                    </Card.Subtitle>
                                    <Card.Subtitle className="mb-2 text-muted">
                                    {val.salaire} €
                                    </Card.Subtitle>
                                    { this.state.showMe?
                                        <div className="description">
                                        <Card.Text>{val.description}</Card.Text>
                                        </div>
                                        :null
                                    }
                                    <Card.Link onClick={()=> this.operation()} id="toto" href="#">Learn more</Card.Link>
                                    <Card.Link href="#">Apply</Card.Link>
                                </Card.Body>
                                
                                
                            </Card>
                        </div>
                    );
                })}

            </div>
        </div>
    )
}
}


我有点知道出了什么问题,当我按下按钮时,我会给每张卡显示 showMe 状态,但我不知道如何解决它! 提前感谢您的帮助。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    将初始 showMe 状态设为 null 并将 operation 转换为获取索引以进行切换。如果索引已经保存在 state 中,则设置回 null。

    operation(index) {
      this.setState({
        showMe: this.state.showMe === index ? null : index,
      })
    }
    

    使用映射索引传递给处理程序并根据showMe 状态检查此索引以显示卡片。

    {this.state.advLists.map((val, key) => {
      return (
        <div className="card_">
          <Card style={{ width: "100%" }}>
            <Card.Body>
              <Card.Title>{val.compName}</Card.Title>
              <Card.Subtitle className="mb-2 text-muted">
                {val.city} | {val.compWebsite}
              </Card.Subtitle>
              <Card.Subtitle className="mb-2 text-muted">
                {val.salaire} €
              </Card.Subtitle>
              {this.state.showMe === key && ( // <-- check if index/key matches
                <div className="description">
                  <Card.Text>{val.description}</Card.Text>
                </div>
              )}
              <Card.Link
                onClick={() => this.operation(key)} // <-- pass key/index to toggle
                id="toto" href="#"
              >
                Learn more
              </Card.Link>
              <Card.Link href="#">Apply</Card.Link>
            </Card.Body>
          </Card>
        </div>
      );
    })}
    

    【讨论】:

    • 谢谢你,这很有效!我正在使用卡的 ID,我非常接近!
    • @AlexisDaCosta 对,使用与数据中的映射元素关联的id 实际上是首选,但因为我没有看到任何看起来在数据集中独一无二的属性,并且我没有在您的代码中看到任何暗示您将使用索引从 this.state.advLists 添加/删除元素(即数组长度是静态的)是一个不错的后备。
    【解决方案2】:

    我可以为您提供有关如何使用 React 类组件切换单个项目的代码模式。

    class MyComponent extends React.Component {
      state = { items: [] }; // initial state
    
      componentDidMount() {
        // fetched data
        this.setState({ items: [{ title: "one" }, { title: "two" }] }); 
      }
    
      toggleItem = (index) => {
        let items = this.state.items;
        items[index].hidden = !items[index].hidden; // mutating
        this.setState({ items }); // new object triggers re-render
      };
    
      render() {
        return (
          <ul>
            {this.state.items.map((item, index) => {
              return (
                <li key={index}> {/* remember to use a key */}
                  <button onClick={() => this.toggleItem(index)}>toggle</button>
    
                  {!item.hidden && item.title}
                </li>
              );
            })}
          </ul>
        );
      }
    }
    

    【讨论】:

    • 非常感谢,我将来可能会使用它!
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多