简体   繁体   English

静态组件不会在执行setState时重新渲染

[英]Static component doesn't rerender doing setState

I have this static Content component that doesn't rerender 我有这个静态的Content组件,不会重新渲染

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

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

But I've no clue why the tab 1 content doesn't hide when I click on the tab 2 title. 但是我不知道为什么当我单击选项卡2标题时,选项卡1的内容没有隐藏。

Here's the demo https://codesandbox.io/s/w2mxm3zjq5 这是演示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. 由于您的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>
  );
};

Working codepen 工作码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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