3
关注
1785
浏览

ReactJS:如何按顺序映射JSON元素并在点击时显示隐藏的div

为什么被折叠? 0 个回复被折叠
阳阳 未验证用户 用户来自于: 广东省
2020-09-16 15:01

Toggle组件应b像这样。

class Toggle extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     isShow: false, 
     id: -1, // initial value 
    }; 
    } 

    handleClick = (id) => { 
    this.setState({ 
     isShow: !this.state.isShow, 
     id: id 
    }); 
    } 

    render() { 
    const { location } = places.library; 
    const { isShow, id } = this.state; 
    return (
     
"control"> {location.map((libr, index) => (
{ this.handleClick(index) }}>

{libr.loc_name}

{(isShow && (id === index)) &&

{libr.desc}

}
))}
); } }

所以,当你点击div元素。点击事件将被触发,称为​​,它将传递index作为该函数的参数。这会将isShow设置为false或truth,反之亦然,以及要显示的当前元素将通过this.state.id进行选择。所以每次isShow为真,this.state.id匹配index数组的元素。您的描述将显示,否则它会隐藏,只要你想。

所以你想要的结果会是这样的。

library1 
desc1 : Modern and spacious building (hidden but shown when clicked) 

library2 
desc 2 : A cosy small building (hidden but shown when clicked) 
苹果_love 未验证用户 用户来自于: 广东省
2020-09-16 05:34

我可能会尝试将位置提取到单独的组件中。通过提取它,每个位置负责了解其状态。在你的情况下,这意味着它的可见性(由this.state.isShow控制)。

这里是你如何能做到这一点:

import React from 'react'; 
import { render } from 'react-dom'; 

var places = { 
    library: { 
    location: [ 
     { 
     loc_name: "library1", 
     "desc": "Modern and spacious building" 
     }, 
     { 
     loc_name: "library2", 
     "desc": "A cosy small building" 
     } 
    ] 
    } 
}; 

class Location extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { isShow: false }; 
    this.handleClick = this.handleClick.bind(this); 
    } 

    handleClick() { 
    this.setState(function (prevState) { 
     return { isShow: !prevState.isShow }; 
    }); 
    } 

    contentClass(isShow) { 
    if (isShow) { 
     return "content"; 
    } 
    return "content invisible"; 
    } 

    render() { 
    return (
     
'control' onClick={this.handleClick}>

{this.props.desc}

this.contentClass(this.state.isShow)}>{this.props.loc_name}
) } } class Toggle extends React.Component { constructor(props) { super(props); } render() { const locations = places.library.location.map(location => { return }) return (
{locations}
); } } render(( ), document.getElementById('root'));

关于作者

问题动态

发布时间
2020-09-15 15:51
更新时间
2022-09-15 15:51
关注人数
3 人关注

相关问题

请问如何求出下列excel表格中的数值
如何传递一个变量在web API
请问UDI数据库里的用户如何进行删除呢?
如何看待亚马逊员工受贿导致内部数据泄漏,中国区高管被重新洗牌一事?
如何搭建一个融合通信展厅?
如何让技术再次实现创新升级?
按键精灵如何在找到颜色后再次确认并进行触发?
将数组映射到Typescript/Angular中的对象
如何使用querySelector
如何设置独立服务器?
个人工作笔记 Powered BY WeCenter V4.1.0 © 2024 粤ICP备2020123311号