我试图从JSON中加载项目,并在点击时使用描述切换下拉div。虽然我可以在静态div上按顺序显示元素(例如:loc1 & desc1, loc2 & desc2
),但在第二部分(desc)隐藏时只能在点击loc loc时显示如何正确渲染它。ReactJS:如何按顺序映射JSON元素并在点击时显示隐藏的div
什么是映射结果的最佳方式,因此它不显示为loc1 & loc2, desc1 & desc2
而是loc1 & desc1, loc2 & desc2
?
代码:
var places = {
library: {
location: [
{
loc_name: "library1",
"desc": "desc1 : Modern and spacious building"
},
{
loc_name: "library2",
"desc": "desc2 : A cosy small building"
}
]
}
};
function contentClass(isShow) {
if (isShow) {
return "content";
}
return "content invisible";
}
class Toggle 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 };
});
}
render() {
const libraries_desc = places.library.location.map((libr) =>
{libr.desc}
);
const lib_names = places.library.location.map((libr) =>
{libr.loc_name}
);
return (
'control' onClick={this.handleClick}>
{lib_names}
this.state.isShow)}>{libraries_desc}
);
}
}
render((
), document.getElementById('root'));
当前的结果:
library1
library2
desc1 : Modern and spacious building
desc 2 : A cosy small building
所需的结果:
library1
desc1 : Modern and spacious building (hidden but shown when clicked)
library2
desc 2 : A cosy small building (hidden but shown when clicked)
Codesandbox
我可能会尝试将位置提取到单独的组件中。通过提取它,每个位置负责了解其状态。在你的情况下,这意味着它的可见性(由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'));
这家伙很懒,还没有设置简介