簡體   English   中英

如何在 JavaScript 中獲得順風活動斷點?

[英]How do I get tailwinds active breakpoint in JavaScript?

我正在使用配置文件構建順風並將其包含在反應項目中。

我想在 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 中獲得相同的結果。?

從 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 將其與您當前的屏幕寬度進行比較。

在這里查看更多。

這是我在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;

如果有人正在尋找一種不使用 tailwind 配置的方法,您可以通過使用 tailwind 的斷點系統來控制幾個 0x0 div 的可見性,並測試這些 div 的可見性以確定當前活動斷點來實現這一點。

例如,你可以在你的 body 中嵌入幾個大小為 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 的實際斷點系統來確定當前處於活動狀態的斷點系統。

對於那些使用 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>
  );

為此,我使用這種和平的代碼:

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

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

我可以像這樣在 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>

在我的 Component.jsx

import React from 'react'

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM