高性能的窗口大小转换 - react-sizes

2017-04-10      290      JavaScript
项目简介

安装

yarn add react-sizes
npm install react-sizes

What and why

React Sizes是一个高级组件,配有高性能的窗口大小转换。

Usage

类组件

import React from 'react';
import Sizes from 'react-sizes';

class MyComponent extends Component {
  render() {
    return (
      <div>{this.props.isMobile ? 'Is Mobile' : 'Is Not Mobile'}</div>
    );
  }
}

const mapSizesToProps = ({ width }) => ({
  isMobile: width < 480,
});

export Sizes(mapSizesToProps)(MyComponent);

作为装饰

import React from 'react';
import Sizes from 'react-sizes';

@Sizes(({ width }) => ({ isMobile: width < 480 }))
class MyComponent extends Component {
  render() {
    return (
      <div>{this.props.isMobile ? 'Is Mobile' : 'Is Not Mobile'}</div>
    );
  }
}

export default MyComponent;

功能部件

import React from 'react';
import Sizes from 'react-sizes';

const MyComponent = ({ isMobile }) => (
  <div>{isMobile ? 'Is Mobile' : 'Is Not Mobile'}</div>
);

const mapSizesToProps = ({ width }) => ({
  isMobile: width < 480,
});

export Sizes(mapSizesToProps)(MyComponent);

与其他库互操作

import React from 'react';
import Sizes from 'react-sizes';
import { withState, compose } from 'recompose';

const enhancer = compose(
  withState('counter', 'setCounter', 0),
  Sizes(({ width }) => ({ isMobile: width < 480 })),
);

const MyComponent = enhancer(({ isMobile, counter, setCounter }) => (
  <div>
    <div>
      Count: {counter} <button onClick={() => setCounter(n => n + 1)}>Increment</button>
    </div>
    <div>{isMobile ? 'Is Mobile' : 'Is Not Mobile'}</div>
  </div>
));

export default MyComponent;