[英]Static component doesn't rerender doing setState
我有这个静态的Content组件,不会重新渲染
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
})
);
}
但是我不知道为什么当我单击选项卡2标题时,选项卡1的内容没有隐藏。
由于您的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>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.