我試圖從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) =>
<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)
它顯示一個語法錯誤,在關閉location.map((溴化鋰,指數)的標籤,即使它正常關閉,之所以會如此 – Amma
它?我錯誤地修改了它,請看代碼中的代碼再次提交methid –
就是這樣 - 現在工作了,謝謝! – Amma