我是第一次与React一起玩,试图弄清楚如何制作标签。我找到了看起来很简洁的代码概要(但是,如果我错了,请更正我),但是我不知道如何在“构造函数”之外显示选项卡的内容。因为我希望制表符的内容不仅仅是几个单词,所以当前代码似乎很狭窄。
这是我正在谈论的部分:
constructor(props) {
super(props);
this.state = {
activeTabIndex: 0,
initialData: [
{
label: 'Tab 1',
content: 'Content 1',
},
{
label: 'Tab 2',
content: 'Content 2',
},
{
label: 'Tab 3',
content: 'Content 3',
},
],
};
this.handleTabClick = this.handleTabClick.bind(this);
}
如果我有太多内容无法放入其中,我该如何将其拉出?这是完整的代码概述:link。欢迎任何建议/链接。
如果我要解释这个错误,我深表歉意,但我仍在努力弄清楚问题。谢谢!
答案 0 :(得分:4)
只需创建要在“标签内容”中呈现的组件,然后将其分配给内容即可。
import React, { Component } from "react";
import Tabs from "./Tabs";
import Content from "./Content";
export default class TabView extends Component {
constructor(props) {
super(props);
this.state = {
activeTabIndex: 0,
initialData: [
{
label: "Tab 1",
content: <TabContent />
},
{
label: "Tab 2",
content: "Content 2"
},
{
label: "Tab 3",
content: "Content 3"
}
]
};
this.handleTabClick = this.handleTabClick.bind(this);
}
handleTabClick(index) {
this.setState({
activeTabIndex: index
});
}
render() {
const { initialData, activeTabIndex } = this.state;
const activeItem = this.state.initialData[activeTabIndex];
return (
<div>
<Tabs
handleTabClick={this.handleTabClick}
data={this.state.initialData}
activeTabIndex={activeTabIndex}
/>
<Content content={activeItem.content} />
</div>
);
}
}
const TabContent = () => (
<div>
<p>I am here</p>
</div>
);
答案 1 :(得分:4)
import React from "react";
import Tabs from "./Tabs";
import Content from "./Content";
class TabLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTabIndex: 0,
initialData: [
{
label: "Tab 1",
content: "Content 1"
},
{
label: "Tab 2",
content: "Content 2"
},
{
label: "Tab 3",
content: "Content 3"
}
]
};
}
componentDidMount() {
this.handleClick = this.handleClick.bind(this);
}
handleClick = (tabIndex) => {
this.setState({
activeTabIndex: tabIndex
});
}
render() {
const activeTab = this.state.initialData[this.state.activeTabIndex];
return (
<div>
<Tabs
handleClick = { this.handleClick }
data = { this.state.initialData }
activeTabIndex = { this.state.activeTabIndex }
/>
<Content content={activeTab.content} />
</div>
);
}
}
export default TabLayout;