react 根据屏幕大小决定视图渲染

包:https://github.com/flexdinesh/react-socks

手动实现:

constructor() {
  super();
  this.state = {
     window.innerWidth,
  };
}

componentWillMount() {
  window.addEventListener('resize', this.handleWindowSizeChange);
}

// make sure to remove the listener
// when the component is not mounted anymore
componentWillUnmount() {
  window.removeEventListener('resize', this.handleWindowSizeChange);
}

handleWindowSizeChange = () => {
  this.setState({  window.innerWidth });
};

render() {
  const { width } = this.state;
  const isMobile = width <= 500;
  // the rest is the same...

  if (isMobile) {
    return (
      <Tabs>
        <Tab><Yellow /></Tab>
        <Tab><Green /></Tab>
        <Tab><Purple /></Tab>
      </Tabs>
    );
  } else {
    return (
      <Columns>
        <Yellow />
        <Green />
        <Purple />
      </Columns>
    );
  }
}
原文地址:https://www.cnblogs.com/elimsc/p/14778985.html