【发布时间】:2020-05-03 16:05:31
【问题描述】:
我需要从 React.Component 中的 JSON 创建一个嵌套的手风琴菜单。对象对象的每个键都必须是在单击时显示嵌套项的按钮(如果值不为空)。我有两个函数可以为键创建按钮和为值创建隐藏的 div,但它们不会出现在 HTML 代码中。
menuItems.json
{
"item1": {
"nestedItem1": null,
"nestedItem2": {
"deeplyNetstedItem1": null
}
},
"item2": null,
"item3": null,
"item4": {
"nestedItem3": null
}
}
DropdownList.jsx (UPD)
import React from "react";
class DropdownList extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data
};
this.createListData = this.createListData.bind(this);
this.createButton = this.createButton.bind(this);
this.createHidden = this.createHidden.bind(this);
}
createButton = (item) => {
return <button className='accordion'>{item}</button>
}
createHidden = (item) => {
return <div className='panel'>{item}</div>
}
createListData = (data) => {
for (let [key, value] of Object.entries(data)) {
if (value && typeof(value) == "object") {
console.log(key, value);
this.createButton(key);
this.createListData(value);
} else {
this.createHidden(key);
console.log(key);
}
}
}
render() {
return <div>{this.createListData(this.state.data)}</div>
}
}
export default DropdownList;
App.js
import React from "react";
import DropdownList from "./DropdownList/DropdownList";
import data from "./menuItems.json";
function App() {
return <DropdownList data={data} />;
}
export default App;
【问题讨论】:
标签: javascript html json reactjs return