Ich versuche Elemente von JSON zu laden und dropdown div mit Beschreibung bei Klick umzuschalten. Während ich Elemente sequentiell (zB: loc1 & desc1, loc2 & desc2
) auf statischen Divs anzeigen kann, habe ich Probleme herauszufinden, wie man es korrekt rendert, wenn der zweite Teil (desc) ausgeblendet ist und nur angezeigt wird, wenn auf das loc div geklickt wird.ReactJS: Wie man JSON Elemente sequentiell abbildet und das versteckte div beim Klick zeigt
Was wäre der beste Weg, das Ergebnis zuzuordnen, so dass es nicht als loc1 & loc2, desc1 & desc2
sondern als loc1 & desc1, loc2 & desc2
angezeigt wird?
Code:
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'));
Aktuelles Ergebnis:
library1
library2
desc1 : Modern and spacious building
desc 2 : A cosy small building
Gewünschtes Ergebnis:
library1
desc1 : Modern and spacious building (hidden but shown when clicked)
library2
desc 2 : A cosy small building (hidden but shown when clicked)
Es ist auf Endtag location.map einen Syntaxfehler zeigt ((libr, Index), auch wenn es richtig zu schließen ist, warum das so sein würde – Amma
es.? fehlte ein '(' am Ende von. map() Ich habe es behoben. guck mal wieder den Code in render methid –
Das wars - jetzt klappt es, danke! – Amma