在 React 组件中使用 tailwind css 主题

问题描述 投票:0回答:1

我想在我的 React 组件中使用顺风主题。为此,我做了这个:

import theme from "tailwindcss/defaultTheme";


console.log(theme)

另外,我创建了

tailwind.config.js
文件,我在其中添加了对主题的新更改。
这样做我遇到了一个问题,因为
console.log(theme)
的值是默认顺风值,即使我覆盖了它们。
如何从顺风主题获取更新的值?

reactjs tailwind-css
1个回答
0
投票

假设我们在

tailwind.config.js
中定义了以下内容:

const colors = require('tailwindcss/colors')

module.exports = {
  theme: {
    colors: {
      white: colors.slate[50],
      dark: colors.slate[900],
    },
  },
  // content: ...
  // plugins: ...
}

现在我们可以在导入配置文件后访问属性

white

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

const color = theme.colors['white']

奖金

创建我们自己的 getter 以在代码中的任何地方使用 tailwind 默认值和我们的配置

import { spacing as defaultSpacing } from 'tailwindcss/defaultTheme'
import { theme } from '../tailwind.config.js' // path may vary

export const getThemeColor = (color) => theme.colors[color]
export const getTailwindSpacing = t => defaultSpacing[`${t}`]

// usage
const someCalculatedValue = 2 * 2

getTailwindSpacing(someCalculatedValue) // -> 1em
getThemeColor('white') // -> #f8fafc

打字稿版本

因为我喜欢这里的打字稿,我的方式让打字检查员开心

import { spacing as defaultSpacing } from 'tailwindcss/defaultTheme'
import { theme } from '../tailwind.config.js' // path may vary

export const getThemeColor = (color: string) => theme.colors[color]
export const getTailwindSpacing = (spacing: number) => {
  const number = `${spacing}` as keyof typeof defaultSpacing
  return defaultSpacing[number]
}

// usage
const someCalculatedValue = 2 * 2

getTailwindSpacing(someCalculatedValue) // -> 1em
getThemeColor('white') // -> #f8fafc
© www.soinside.com 2019 - 2024. All rights reserved.