簡體   English   中英

靜態組件不會在執行setState時重新渲染

[英]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的內容沒有隱藏。

這是演示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>
  );
};

工作碼筆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM