简体   繁体   中英

Static component doesn't rerender doing setState

I have this static Content component that doesn't rerender

  static Content = ({ children, tabId, activeTab }) => {
    return tabId === activeTab ? children : ''
  }

tabId and activeTab is exposed using 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
      })
    );
  }

But I've no clue why the tab 1 content doesn't hide when I click on the tab 2 title.

Here's the demo https://codesandbox.io/s/w2mxm3zjq5

Since your Tab component stores that state, when it is clicked only that particlular compontent state updates and hence the other one doesn't change, you need to lift the state up to the tabs component and it will work.

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>
  );
};

Working codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM