我想使用此功能从我的JSON生成动态标签:
generateTab() {
var tablist = [];
for (var i = 0; i < Object.keys(jsonTest.tabList).length; i++) {
tablist.push(<Tab>{Object.keys(jsonTest.tabList)[i]}</Tab>);
}
return tablist;
}
从这个JSON对象:
var jsonTest = {
"tabList": {
"titre" : "toto",
"Activity" : {
"A1" : {
"titre": "A1 titre",
"test" : "A1 test"
},
"A2" : {
"titre": "A2 titre",
"test" : "A2 test"
}
}
}
};
最后,我的函数应该返回如下内容:
<Tab>titre</Tab>
<Tab>Activity</Tab>
<TabPanel> toto </TabPanel>
<TabPanel>
A1: A1 titre A1 test
A2: A2 titre A2 test
</TabPanel>
关于如何生成第二部分(TabPanel)的任何想法?
答案 0 :(得分:1)
我认为您正在寻找的正确结构是:
<Tabs>
<TabList>
<Tab>titre</Tab>
<Tab>Activity</Tab>
</TabList>
<TabPanel>
toto
</TabPanel>
<TabPanel>
A1: A1 titre A1 test
A2: A2 titre A2 test
</TabPanel>
</Tabs>
您可以在组件中使用以下方法实现此结构:
let jsonTest = {
// ...
};
class YourApp extends Component {
/**
* Flattens the activities object into an array of strings
*
* @param {object} activities the activities configuration object
* @returns {array}
*/
getFlattened(activities) {
let results = [];
for (let key in activities) {
if (activities.hasOwnProperty(key)) {
results.push(
`${key}: ${activities[key].titre} ${activities[key].test}`
);
}
}
return results;
}
/**
* Genrates the tabs component structure
*
* @param {object} config the JSON tab configuration
* @returns {JSX.Element}
*/
generateTabs(config) {
if (!config || !config instanceof Object) {
return null;
}
let tabs = [];
let tabPanels = [];
for (let key in config) {
if (config.hasOwnProperty(key)) {
tabs.push(
<Tab>
{ key }
</Tab>
);
if (config[key] instanceof Object) {
tabPanels.push(
<TabPanel>
{ this.getFlattened(config[key]) }
</TabPanel>
);
}
else {
tabPanels.push(
<TabPanel>
{ config[key] }
</TabPanel>
);
}
}
}
return (
<Tabs>
<TabList>
{ ...tabs }
</TabList>
{ ...tabPanels }
</Tabs>
);
}
/**
* React Lifecycle Rendering Method
*
* @returns {JSX.Element}
*/
render() {
return (
<div>
{/* maybe other stuff here */}
{ this.generateTabs(jsonTest) }
{/* maybe other stuff here */}
</div>
);
}
}