@4react/responsive 中文文档教程

发布于 4年前 浏览 29 项目主页 更新于 3年前

@4react / responsive

React 应用程序的响应能力。

npm i @4react/responsive

Usage

Define breakpoints

import { ResponsiveProvider } from '@4react/responsive'

const App = () => (
  <ResponsiveProvider breakpoints={{
    mobile: 0,
    tablet: 768,
    desktop: 992
  }}>
    ...
  </ResponsiveProvider>
)

Create responsive values

import { useResponsive } from '@4react/responsive'

const Foo = () => {
  const responsive = useResponsive()
  const width = responsive(['100%', 720, 960])

  return (
    <div style={{ width }}>
      ...
    </div>
  )
}

Render components conditionally

import { Responsive } from '@4react/responsive'

const App = () => (
  <Container>
    <Responsive condition={{ max: 'tablet' }}>
      <MobileMenu />      
    </Responsive>
    <Responsive condition="desktop">
      <NavBar />
    </Responsive>
  </Container>
)

API

Components
Hooks

ResponsiveProvider [Component]

使用此组件为应用程序提供响应功能。

PropsTypeDefaultDescription
breakpointsobject (see Breakpoints definition)see Default breakpoints[optional] Custom breakpoints configuration.

Breakpoints definition

可以使用具有以下特征的对象映射来配置断点:

  • each key represent a custom breakpoint name
  • each value represents the minimum width for corresponding breakpoint.
{ tablet: 768, desktop: 992 }

上面的示例指定了 2 个值; 相应定义的断点是:

  • tablet: 768 pixels and above.
  • desktop: 992 pixels and above.

然而,第三个断点是隐式定义的,并将自动命名为“default”:

  • default: 0 and above. Fallback value if no breakpoint is currently matching the screen resolution.

无论如何,可以定义自定义名称,即使是默认断点。 只需将其定义为值 0。

{ mobile: 0, tablet: 768, desktop: 992 }

在这种情况下,断点将是:

  • mobile: 0 pixels and above.
  • tablet: 768 pixels and above.
  • desktop: 992 pixels and above.

注意: 指定值的顺序不影响断点顺序。 值将按升序排序。

Default breakpoints

如果没有指定断点模式,将使用以下值:

{ xs: 480, sm: 576, md: 768, lg: 992, xl: 1200, xxl: 1600 }

Responsive [Component]

使用此组件有条件地呈现应用程序的某些部分。

// with children
<Responsive condition={...}>
  <Content />
</Responsive>

// with component prop
<Responsive condition={...} component={Content} />

// with render prop
<Responsive condition={...} render={
  (breakpoint) => <Content breakpoint={breakpoint}/>
} />
PropsTypeDefaultDescription
conditionstring | array | object (see Responsive condition)-Defines the render condition.
componentReact Component-[optional] Render the specified component.
renderRender Function-[optional] Render function, receiving the current active breakpoint.
Responsive condition

响应条件可以用 3 种方式描述:

使用 string 表示特定断点的名称。

<Responsive condition="mobile" ... />

使用 array of string 表示断点名称列表。

<Responsive condition={['xs', 'xxl']} ... />

使用包含以下一个或多个键的对象

  • min:string representing the minimum breakpoint for which the condition is valid.
  • max:string representing the maximum breakpoint for which the condition is valid.
<Responsive condition={{ min: 'lg' }} ... />
<Responsive condition={{ min: 'sm', max: 'lg' }} ... />

useResponsive [hook]

调用此挂钩以获得响应 函数,用于创建断点相关值。

const responsive = useResponsive()
ParamTypeDefaultDescription
breakpointsarray-[optional] Select a subset of breakpoints for which the responsive function will work (see Select a subset of breakpoints).

响应函数将一组值作为参数并返回要考虑当前有效断点的值。 让我们考虑在断点定义 示例中使用的相同 3 断点架构。

下面的示例为每个定义的断点指定一个值。

// with default breakpoint
const width = responsive({ default: '100%', tablet: 720, desktop: 950 })

// without default breakpoint
const width = responsive({ mobile: '100%', tablet: 720, desktop: 950 })

也可以使用数组速记。 按照自然排序,值将关联到相应位置的断点。

const width = responsive(['100%', 720, 950])

在上面的示例中,数组中的第二个值 (720) 将引用第二个断点 (tablet)。

注意: responsive 函数也可以用一个简单的值(stringnumber)调用。 在这种情况下,值只是返回而没有任何附加逻辑。

很多时候你想管理一个响应属性而不为每个可能的断点指定值 例如,当断点从平板电脑变为桌面时,可见性 属性可从“可见” 设置为“隐藏”。 在这些情况下,我们可以简单地忽略不感兴趣的断点。

const visibility = responsive({ mobile: 'visible', desktop: 'hidden' })
// is the same of
const visibility = responsive({ mobile: 'visible', tablet: 'visible', desktop: 'hidden' })

上面两行创建相同的响应值。 在这种情况下,没有必要为 tablet 断点指定一个值; tablet 将自动维护为 mobile 断点声明的值。

通常,响应值将用于指定的断点和所有后续断点,直到为后续断点找到另一个值。

这是另一个使用默认配置的示例,请参阅默认断点)。

const height = responsive({ default: 32, md: 40, xxl: 48 })

在这种情况下:

  • default, xs and sm will take both value 32.
  • md, lg and xl will all take value 40.
  • xxl will take value 48.

注意: 使用数组表示法,您必须为每个断点声明一个值。 跳过一个值将导致相应位置的断点具有值 undefined。 无论如何,您可以在断点子集上使用此表示法(请参阅选择断点子集

Select a breakpoints subset

如果需要,我们可以使用 useResponsive 可选参数来指定所需的断点子集; 这可以通过列出它们的名称来完成:

const responsive = useResponsive(['default', 'md', 'xxl'])

const width = responsive([32, 40, 48])

在上面的示例中,响应函数将采用一个包含 3 个值的数组,对应于使用 hook 参数选择的 3 个断点。

useResponsiveCondition [hook]

使用此挂钩使用响应组件的相同条件逻辑创建布尔检查(请参阅响应组件)。

ParamTypeDefaultDescription
breakpointsstring | array | object (See Responsive Component)-Specify the checker condition.
// single breakpoint
const isMobile = useResponsiveCondition('mobile')
// list of breakpoints
const isMobile = useResponsiveCondition(['xs', 'sm', 'md'])
// configuration objet
const isMobile = useResponsiveCondition({ max: 'md' })

useCurrentBreakpoint [hook]

使用此挂钩获取实际有效的断点。

const current = useCurrentBreakpoint()

useIsBreakpointDetected [hook]

在运行时检测到断点。 使用此挂钩检查在第一次应用程序呈现期间是否仍要检测到断点。

const isBreakpointDetected = useIsBreakpointDetected()

if (!isBreakpointDetected) {
  render <Loader />
}

render <App />

@4react / responsive

Responsiveness for React Applications.

npm i @4react/responsive

Usage

Define breakpoints

import { ResponsiveProvider } from '@4react/responsive'

const App = () => (
  <ResponsiveProvider breakpoints={{
    mobile: 0,
    tablet: 768,
    desktop: 992
  }}>
    ...
  </ResponsiveProvider>
)

Create responsive values

import { useResponsive } from '@4react/responsive'

const Foo = () => {
  const responsive = useResponsive()
  const width = responsive(['100%', 720, 960])

  return (
    <div style={{ width }}>
      ...
    </div>
  )
}

Render components conditionally

import { Responsive } from '@4react/responsive'

const App = () => (
  <Container>
    <Responsive condition={{ max: 'tablet' }}>
      <MobileMenu />      
    </Responsive>
    <Responsive condition="desktop">
      <NavBar />
    </Responsive>
  </Container>
)

API

Components
Hooks

ResponsiveProvider [Component]

Use this component to provide responsiveness functionalities down to the application.

PropsTypeDefaultDescription
breakpointsobject (see Breakpoints definition)see Default breakpoints[optional] Custom breakpoints configuration.

Breakpoints definition

Breakpoints can be configured with an object map with the following characteristics:

  • each key represent a custom breakpoint name
  • each value represents the minimum width for corresponding breakpoint.
{ tablet: 768, desktop: 992 }

The example above specifies 2 values; the corresponding defined breakpoints are:

  • tablet: 768 pixels and above.
  • desktop: 992 pixels and above.

Nevertheless, a third breakpoint is implicitly defined, and will be automatically named "default":

  • default: 0 and above. Fallback value if no breakpoint is currently matching the screen resolution.

Anyway, it's possible to define a custom name, even for the default breakpoint. Just define it with value 0.

{ mobile: 0, tablet: 768, desktop: 992 }

In this case, breakpoints will be:

  • mobile: 0 pixels and above.
  • tablet: 768 pixels and above.
  • desktop: 992 pixels and above.

NOTE: The order in which values are specified does not influence breakpoints order. Values will be sorted in ascending order.

Default breakpoints

In case of no breakpoints' schema specified, the following values will be used:

{ xs: 480, sm: 576, md: 768, lg: 992, xl: 1200, xxl: 1600 }

Responsive [Component]

Use this component to conditionally render parts of your application.

// with children
<Responsive condition={...}>
  <Content />
</Responsive>

// with component prop
<Responsive condition={...} component={Content} />

// with render prop
<Responsive condition={...} render={
  (breakpoint) => <Content breakpoint={breakpoint}/>
} />
PropsTypeDefaultDescription
conditionstring | array | object (see Responsive condition)-Defines the render condition.
componentReact Component-[optional] Render the specified component.
renderRender Function-[optional] Render function, receiving the current active breakpoint.
Responsive condition

A responsive condition can be described in 3 ways:

With a string representing the name of a specific breakpoint.

<Responsive condition="mobile" ... />

With an array of string representing a list of breakpoints names.

<Responsive condition={['xs', 'xxl']} ... />

With an object containing one or more of the following keys:

  • min:string representing the minimum breakpoint for which the condition is valid.
  • max:string representing the maximum breakpoint for which the condition is valid.
<Responsive condition={{ min: 'lg' }} ... />
<Responsive condition={{ min: 'sm', max: 'lg' }} ... />

useResponsive [hook]

Call this hook to obtain the responsive function, used for creating breakpoint-dependent values.

const responsive = useResponsive()
ParamTypeDefaultDescription
breakpointsarray-[optional] Select a subset of breakpoints for which the responsive function will work (see Select a subset of breakpoints).

The responsive function takes a set of values as argument and returns the value to consider for the current valid breakpoint. Let's consider the same 3-breakpoints schema used in Breakpoints definition example.

The example below specifies a value for each defined breakpoint.

// with default breakpoint
const width = responsive({ default: '100%', tablet: 720, desktop: 950 })

// without default breakpoint
const width = responsive({ mobile: '100%', tablet: 720, desktop: 950 })

It's also possible to use the array shorthand. Values will be associated to the breakpoint in the corresponding position, following the natural sorting.

const width = responsive(['100%', 720, 950])

In the example above, the second value in the array (720) will refer to the second breakpoint (tablet).

NOTE: The responsive function can also be called with a simple value (string or number). In this case the value is simply returned without any additional logic.

Many times you want to manage a responsive property without specifying values for each possible breakpoint e.g. a visibility property to set from "visible" to "hidden" when breakpoint change from tablet to desktop. In these cases, we can simply ignore non interesting breakpoints.

const visibility = responsive({ mobile: 'visible', desktop: 'hidden' })
// is the same of
const visibility = responsive({ mobile: 'visible', tablet: 'visible', desktop: 'hidden' })

Both the above lines creates the same responsive value. In this case specifying a value for the tablet breakpoint is not necessary; tablet will automatically maintain the value declared for mobile breakpoint.

In general, a responsive value will be used for the specified breakpoint and for all the following, until another value will be found for a subsequent breakpoint.

Here another example using the default configuration see Default Breakpoints).

const height = responsive({ default: 32, md: 40, xxl: 48 })

In this case:

  • default, xs and sm will take both value 32.
  • md, lg and xl will all take value 40.
  • xxl will take value 48.

NOTE: Using the array notation you are forced to declare a value for each breakpoint. Skipping a value will cause the breakpoint in the corresponding position to have value undefined. Anyway you can use this notation on a subset of breakpoints (See Select a breakpoints subset)

Select a breakpoints subset

If needed, we can use the useResponsive optional parameter to specify a desired subset of breakpoints; this can be done listing their names:

const responsive = useResponsive(['default', 'md', 'xxl'])

const width = responsive([32, 40, 48])

In the above example, the responsive function will take an array of 3 values, corresponding to the 3 breakpoints selected with the hook parameter.

useResponsiveCondition [hook]

Use this hook to create boolean checks using the same condition logics of the Responsive component (See Responsive Component).

ParamTypeDefaultDescription
breakpointsstring | array | object (See Responsive Component)-Specify the checker condition.
// single breakpoint
const isMobile = useResponsiveCondition('mobile')
// list of breakpoints
const isMobile = useResponsiveCondition(['xs', 'sm', 'md'])
// configuration objet
const isMobile = useResponsiveCondition({ max: 'md' })

useCurrentBreakpoint [hook]

Use this hook to obtain the actual valid breakpoint.

const current = useCurrentBreakpoint()

useIsBreakpointDetected [hook]

Breakpoint is detected at runtime. Use this hook to check if a breakpoint is still to be detected during the first application render.

const isBreakpointDetected = useIsBreakpointDetected()

if (!isBreakpointDetected) {
  render <Loader />
}

render <App />
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文