简体   繁体   English

如何显示列表的单个隐藏元素并隐藏 rest

[英]How to show single hidden element of list and hide the rest

I have a column list of elements, and each of them has hidden div, I want to show hidden element on click, but when I'm clicking another div, I want to hide current and show the one I clicked last, how can I do it correctly?我有一个元素的列列表,每个元素都有隐藏的 div,我想在点击时显示隐藏的元素,但是当我点击另一个 div 时,我想隐藏当前并显示我最后点击的那个,我怎么能做对了吗?

You could have two specific classes, one that hides element and one that shows element.你可以有两个特定的类,一个隐藏元素,一个显示元素。 when clicking on the element you can use jQuery or JavaScript to toggle the class that shows element for the hidden div of that specific element and hide everything for any other div.单击元素时,您可以使用 jQuery 或 JavaScript 来切换 class 显示该特定元素的隐藏 div 的元素并隐藏任何其他 div 的所有内容。

The component you're rendering could take in an active prop and only render the second div if this prop is true.您正在渲染的组件可以采用活动道具,并且如果该道具为真,则仅渲染第二个 div。

With this, you could then keep track of which element is selected in the parent.这样,您就可以跟踪在父项中选择了哪个元素。

I threw together a working example with very simple content我整理了一个内容非常简单的工作示例

import React, { useState } from 'react';

const ListItem = ({id, isActive, handleClick}) => {
    return (
        <div id={id} onClick={handleClick}>
        Here is the element
            {!!isActive && <div>I am the selected element</div>}
        </div>
    );
};

export const List = () => {
    const [selectedItem, setSelectedItem] = useState();
    const items = ['one', 'two', 'three'];
    
    const handleClick = (event) => {
        setSelectedItem(event.target.id);
    }

    return (
        <div>
            {items.map(item => (
                <ListItem id={item} isActive={item===selectedItem} handleClick={handleClick}/>
            ))}
        </div>
    )
}

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

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