如何在JavaScript中获得tailwinds活动断点?

uttx8gqw  于 2023-04-28  发布在  Java
关注(0)|答案(6)|浏览(255)

我用配置文件构建顺风,并将其包含在react项目中。
我想在javascript/React中获取活动断点值。我怎么能做到同样的。?

<div class="block  sm:hidden md:hidden lg:hidden xl:hidden">al</div>
  <div class="hidden sm:block  md:hidden lg:hidden xl:hidden">sm</div>
  <div class="hidden sm:hidden md:block  lg:hidden xl:hidden">md</div>
  <div class="hidden sm:hidden md:hidden lg:block  xl:hidden">lg</div>
  <div class="hidden sm:hidden md:hidden lg:hidden xl:block">xl</div>
</div>

上面显示了活动断点。但是我如何在js中获得相同的内容而不包括任何上述标记。?

bksxznpy

bksxznpy1#

在tailwind文档中,您可以从tailwindcss节点模块导入配置:

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'

const fullConfig = resolveConfig(tailwindConfig)

fullConfig.theme.width[4]
// => '1rem'

fullConfig.theme.screens.md
// => '768px'

fullConfig.theme.boxShadow['2xl']
// => '0 25px 50px -12px rgba(0, 0, 0, 0.25)'

正如你在上面看到的,你可以通过引用fullConfig.theme.screens.{breakpoint}来获得断点。你应该可以使用javascript将其与当前屏幕宽度进行比较。
在这里找到官方的顺风描述。

rm5edbpk

rm5edbpk2#

下面是我在Typescript中编写的代码,它根据设备宽度返回当前断点。您可以将其放置在独立文件中,并在任何文件中随时导入方法:

import resolveConfig from 'tailwindcss/resolveConfig';
import tailwindConfig from './tailwind.config'; // Fix the path

const fullConfig = resolveConfig(tailwindConfig);

export const getBreakpointValue = (value: string): number =>
  +fullConfig.theme.screens[value].slice(
    0,
    fullConfig.theme.screens[value].indexOf('px')
  );

export const getCurrentBreakpoint = (): string => {
  let currentBreakpoint: string;
  let biggestBreakpointValue = 0;
  for (const breakpoint of Object.keys(fullConfig.theme.screens)) {
    const breakpointValue = getBreakpointValue(breakpoint);
    if (
      breakpointValue > biggestBreakpointValue &&
      window.innerWidth >= breakpointValue
    ) {
      biggestBreakpointValue = breakpointValue;
      currentBreakpoint = breakpoint;
    }
  }
  return currentBreakpoint;
};

**编辑:**在较新的Typescript版本中,您必须将这两个参数添加到compilerOptions下的tsconfig.json中,以便能够导入js文件:

"compilerOptions": {
  "allowJs": true,
  "allowsyntheticdefaultimports": true
}

另外,如果你在Angular上得到了process未定义的错误,你必须将这些行添加到polyfills.ts文件的末尾(当然你必须安装process包):

import * as process from 'process';
window['process'] = process;
c3frrgcw

c3frrgcw3#

这里有一个使用TypeScript 4的小钩子。5+。它基于react-responsive包中的useMediaQuery钩子。随便修改!

import { useMediaQuery } from 'react-responsive';
import { theme } from '../../tailwind.config'; // Your tailwind config

const breakpoints = theme.screens;

type BreakpointKey = keyof typeof breakpoints;

export function useBreakpoint<K extends BreakpointKey>(breakpointKey: K) {
  const bool = useMediaQuery({
    query: `(min-width: ${breakpoints[breakpointKey]})`,
  });
  const capitalizedKey = breakpointKey[0].toUpperCase() + breakpointKey.substring(1);
  type Key = `is${Capitalize<K>}`;
  return {
    [`is${capitalizedKey}`]: bool,
  } as Record<Key, boolean>;
}

在你的组件内部,像这样使用它

const { isSm } = useBreakpoint('sm');
const { isMd } = useBreakpoint('md');
const { isLg } = useBreakpoint('lg');
return (
      <div>
        {isSm && (
          {/* Visible for sm: (min-width: 640px) */}
          <div>Content</div>
        )}

        {isMd && (
          {/* Visible for md: (min-width: 768px) */}
          <div>Content</div>
        )}
      </div>
  );
axzmvihb

axzmvihb4#

如果有人正在寻找一种不使用tailwind配置的方法,可以通过使用tailwind的断点系统来控制几个0x0 div的可见性,并测试这些div的可见性以确定当前活动的断点来实现这一点。
例如,您可以在身体中嵌入几个大小为0的div,如下所示:

<div id="breakpoint-sm" class="hidden sm:block md:hidden lg:hidden xl:hidden 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-md" class="hidden sm:hidden md:block lg:hidden xl:hidden 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-lg" class="hidden sm:hidden md:hidden lg:block xl:hidden 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-xl" class="hidden sm:hidden md:hidden lg:hidden xl:block 2xl:hidden w-0 h-0"></div>
<div id="breakpoint-2xl" class="hidden sm:hidden md:hidden lg:hidden xl:hidden 2xl:block w-0 h-0"></div>

然后,您可以编写一个函数来查找这些元素,并通过每个元素的offsetParent属性检查它们是否可见:

const getCurrentBreakpoint = (): string => {
    const breakpointUnknown: string = 'unknown';
    const breakpointSM: string | null = document.getElementById('breakpoint-sm')?.offsetParent === null ? null : 'sm';
    const breakpointMD: string | null = document.getElementById('breakpoint-md')?.offsetParent === null ? null : 'md';
    const breakpointLG: string | null = document.getElementById('breakpoint-lg')?.offsetParent === null ? null : 'lg';
    const breakpointXL: string | null = document.getElementById('breakpoint-xl')?.offsetParent === null ? null : 'xl';
    const breakpoint2XL: string | null = document.getElementById('breakpoint-2xl')?.offsetParent === null ? null : '2xl';
    const breakpoint = breakpointSM ?? breakpointMD ?? breakpointLG ?? breakpointXL ?? breakpoint2XL ?? breakpointUnknown;
    return breakpoint;
};

现在,您可以测试当前断点字符串以执行一些逻辑:

const breakpoint = getCurrentBreakpoint();
const desktopBreakpoints: string[] = ['sm', 'md', 'lg', 'xl'];
if (desktopBreakpoints.includes(breakpoint)) {
   // On Desktop (in Tailwind's eyes)
} else {
   // On Mobile (in Tailwind's eyes)
}

您需要确保Tailwind使用的任何断点都应用于文档中可以获得的某个0x0 div,并在getCurrentBreakpoint()函数中检查这些断点。但这可以完成工作,而不需要检查Tailwind的配置,并使用Tailwind的实际断点系统来确定哪个是当前活动的。

mf98qq94

mf98qq945#

为了这个目的,我使用了这个和平的代码:

import { theme } from '../../tailwind.config';

export function getCurrentBreakpoints() {
    return Object.keys(theme.screens).find((key) => window.innerWidth > theme.screens[key]);
}
but5z9lq

but5z9lq6#

我可以在React中这样解决这个问题:

{/* MOBILE FIRST */}
<div className="sm:hidden">
  <Component breakpoint="mobile" />
</div>

{/* SMALL */}
<div className="hidden sm:block md:hidden">
  <Component breakpoint="sm" />
</div>

{/* MEDIUM */}
<div className="hidden md:block lg:hidden">
  <Component breakpoint="md" />
</div>

{/* LARGE */}
<div className="hidden lg:block xl:hidden">
  <Component breakpoint="xl" />
</div>

{/* EXTRA LARGE */}
<div className="hidden xl:block 2xl:hidden">
  <Component breakpoint="xl" />
</div>

在我的组件。jsx

import React from 'react'

const Component = (prop) => {
  const { breakpoint } = prop;
  return (
    <div>{breakpoint}</div>
  )
}
export default Component

相关问题