[英]React tabbed content based on dynamic data
我正在尝试根据本教程构建一些选项卡式内容。 当我完全按照教程设置我的应用程序时,一切都很好。 问题是我想用动态内容构建这些选项卡,有时一个或多个选项卡没有任何内容,所以我试图根据传入的数据生成选项卡。
这是我尝试过的:
let tab1 = "Tab 1";
let tab2 = "Tab 2";
let tab3 = false;
let tab4 = "Tab 4";
class Gallery extends Component {
render() {
let tabs;
if (tab1) {
tabs += (
<div label="Gator">
See ya later, <em>Alligator</em>!
</div>
);
}
if (tab2) {
tabs += (
<div label="Croc">
After 'while, <em>Crocodile</em>!
</div>
);
}
if (tab3) {
tabs += (
<div label="Sarcosuchus">
Nothing to see here, this tab is <em>extinct</em>!
</div>
);
}
if (tab4) {
tabs += (
<div label="Gator">
See ya later, <em>Alligator</em>!
</div>
);
}
return (
// THIS WORKS
<Tabs>
<div label="Gator">
See ya later, <em>Alligator</em>!
</div>
<div label="Croc">
After 'while, <em>Crocodile</em>!
</div>
<div label="Sarcosuchus">
Nothing to see here, this tab is <em>extinct</em>!
</div>
</Tabs>
// THIS DOESN'T
// <Tabs>
// {tabs}
// </Tabs>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Gallery />, rootElement);
如果您在 Tabs 组件中注释掉硬编码的子 div 并取消注释我使用tabs
变量的那个,您可以看到有一个错误。 错误是TypeError: Cannot read property 'label' of undefined
on line 15
of Tabs/index.js
所以看起来在设置activeTab
状态之前没有呈现子项。 无论如何,也许我对这一切都做错了。 有没有更好的方法来动态填充这些选项卡?
请注意,在我的实际实现中,tab1/2/3 实际上是 JSON,我只是将它们硬编码为这个问题的变量。
您希望您的孩子成为一个“数组”,因此仅连接 JSX 是行不通的。
您需要使用这些 JSX 元素创建一个数组并作为子项传入
class Gallery extends Component {
render() {
let tabs = [];
if (tab1) {
tabs.push(
<div label="Gator">
See ya later, <em>Alligator</em>!
</div>
);
}
if (tab2) {
tabs.push(
<div label="Croc">
After 'while, <em>Crocodile</em>!
</div>
);
}
if (tab3) {
tabs.push(
<div label="Sarcosuchus">
Nothing to see here, this tab is <em>extinct</em>!
</div>
);
}
if (tab4) {
tabs.push(
<div label="Gator">
See ya later, <em>Alligator</em>!
</div>
);
}
return (
// THIS WORKS
// <Tabs>
// <div label="Gator">
// See ya later, <em>Alligator</em>!
// </div>
// <div label="Croc">
// After 'while, <em>Crocodile</em>!
// </div>
// <div label="Sarcosuchus">
// Nothing to see here, this tab is <em>extinct</em>!
// </div>
// </Tabs>
// THIS DOESN'T
<Tabs>{tabs}</Tabs>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.