【发布时间】:2018-06-08 10:33:29
【问题描述】:
我正在尝试从 JSON 加载项目并在单击时切换带有描述的下拉 div。虽然我可以在静态 div 上按顺序显示元素(例如:loc1 & desc1, loc2 & desc2),但当第二部分(desc)被隐藏并且仅在单击 loc 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) =>
<div>
<p>{libr.desc}</p>
</div>
);
const lib_names = places.library.location.map((libr) =>
<div>
<p>{libr.loc_name}</p>
</div>
);
return (
<div>
<div className='control' onClick={this.handleClick}>
<h4>{lib_names}</h4>
<div className={contentClass(this.state.isShow)}>{libraries_desc}</div>
</div>
</div>
);
}
}
render((
<Toggle />
), 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)
【问题讨论】:
标签: javascript json reactjs loops