我有这个静态内容组件,它不会重新渲染
static Content = ({ children, tabId, activeTab }) => {
return tabId === activeTab ? children : ''
}
tabId 和 activeTab 使用 React.cloneElement 公开。
render() {
return React.Children.map(this.props.children, child =>
React.cloneElement(child, {
handleTabClick: this.handleTabClick,
tabId: this.props.id,
activeTab: this.state.activeTab
})
);
}
但是我不知道为什么当我单击选项卡 1 标题时选项卡 2 内容没有隐藏。
这是演示 https://codesandbox.io/s/w2mxm3zjq5
由于您的 Tab 组件存储该状态,因此当仅单击它时,该特定强制状态会更新,因此另一个状态不会更改,因此您需要将状态提升到 tabs 组件,它将起作用。
class Tab extends Component {
static Title = ({ children, handleTabClick, tabId }) => {
return <div onClick={() => handleTabClick(tabId)}>{children}</div>;
};
static Content = ({ children, tabId, activeTab }) => {
console.log(tabId, "a", activeTab);
return tabId === activeTab ? children : "";
};
render() {
return React.Children.map(this.props.children, child =>
React.cloneElement(child, {
handleTabClick: this.props.handleTabClick,
tabId: this.props.id,
activeTab: this.props.activeTab
})
);
}
}
class Tabs extends React.Component {
state = {
activeTab: this.props.activeTab
};
handleTabClick = id => {
this.setState({
activeTab: id
});
};
render() {
const { children, activeTab } = this.props;
return React.Children.map(children, child =>
React.cloneElement(child, {
activeTab: this.state.activeTab,
handleTabClick: this.handleTabClick
})
);
}
}
const App = () => {
return (
<Tabs activeTab={1}>
<Tab id={1}>
<Tab.Title>Tab 1</Tab.Title>
<Tab.Content>Tab 1 content goes here</Tab.Content>
</Tab>
<Tab id={2}>
<Tab.Title>Tab 2</Tab.Title>
<Tab.Content>Tab 2 content goes here</Tab.Content>
</Tab>
</Tabs>
);
};
工作代码笔