主题

@cfxjs/react-ui 现在也支持 暗黑模式。你可以通过非常简单的 API 随时切换主题,所有的色彩和排版细节都已内置, 不需要任何配置与第三方库。

切换主题

note:在使用任何组件前,请确保已添加 CfxProvider 至应用的根节点。
note:CssBaseline 提供了基础的 CSS 样式,这和你熟悉的 normalize 有些类似。

现在你可以根据如下所示步骤切换主题:

  1. 确保 CfxProviderCssBaseline 已经添加至根节点。

  2. (可选的) 通过钩子 useTheme 获取所有可用的主题变量。

  3. 更新 theme.type 的值,所有的组件都会随之自动变化。

import { CssBaseline, CfxProvider } from '@cfxjs/react-ui'

const App = () => {
  const [themeType, setThemeType] = useState('dark')
  const switchThemes = () => {
    setThemeType(lastThemeType => (lastThemeType === 'dark' ? 'light' : 'dark'))
  }
  return (
    <CfxProvider theme={{ type: themeType }}>
      <CssBaseline />
      <YourComponent onClick={switchThemes} />
    </CfxProvider>
  )
}

自定义主题

自定义主题样式在 @cfxjs/react-ui 中是非常简单的,你只需要提供一个新的样式对象给 CfxProvider,所有的组件都会自然变化以适应你自定义的属性。 这里有 一个完整的示例项目 可供参考。

当然,如果一个组件未使用到你自定义的变量,它不会发生任何变化也不会重新渲染。

note:自定义越多的主题,就会有越多的 重新渲染 发生。
import { CssBaseline, CfxProvider } from '@cfxjs/react-ui'

const myTheme = {
  palette: {
    success: '#000',
  },
}

const App = () => (
  <CfxProvider theme={myTheme}>
    <CssBaseline />
    <YourAppComponent onClick={switchThemes} />
  </CfxProvider>
)

查看主题定义的所有类型

如果你正在使用 TypeScript,可以选择引入各类预置的类型:

import {
  CfxUIThemes,
  CfxUIThemesFont,
  CfxUIThemesPalette,
  CfxUIThemesExpressiveness,
  CfxUIThemesLayout,
} from '@cfxjs/react-ui'

// 使用示例
const myStyles: CfxUIThemes = {
  /* ... */
}
const myPalette: Partial<CfxUIThemesPalette> = {
  /* ... */
}

如果你没有使用 TypeScript,想要了解更多的预置类型,请看这里的类型声明文件

定制化组件

通过 className 重写样式

你可以通过组件上的 className 属性重写当前组件的样式。

import { Button, Row } from '@cfxjs/react-ui'

const MyPage = () => (
  <Row>
    <Button className="page-button">Click me!</Button>
  </Row>
)

// in css file:
.page-button {
  padding: 0;
}

通过行内样式覆盖样式

任何 inline-style (行内样式) 都可以在所有组件上正常的工作。

const MyPage = () => (
  <Row>
    <Button style={{ margin: '20px' }}>Click me!</Button>
  </Row>
)

使用预置主题构建自己的组件

有时候你想要创建一些适用于自己的组件,但你想要跟随整个组件库的主体风格或明暗变化。 现在你可以使用 主题变量 来完成这件事。

import { useTheme } from '@cfxjs/react-ui'

const currentTheme = useTheme()

const MyComponent = () => (
  <div style={{ color: currentTheme.palette.success }}>
    <span>hello world!</span>
  </div>
)