Reactjs 使用样式化组件定义组件变体时的最佳实践?

Reactjs 使用样式化组件定义组件变体时的最佳实践?,reactjs,styled-components,Reactjs,Styled Components,通常,当我使用样式化组件时,我会在globals.js文件中定义一组标准组件,并从那里导出它们。G这样的标准段落样式: export const P = styled.p` font-size: 1.4rem; ` 每种标准款式都可能有不同的款式。G标准的粗体段落。我想知道实现这一目标的最佳方式是什么。我可以看到几种方法: 方式1(传递粗体道具): const P = styled.p` font-weight: ${({fontWeight}) => fontWeigh

通常,当我使用样式化组件时,我会在globals.js文件中定义一组标准组件,并从那里导出它们。G这样的标准段落样式:

export const P = styled.p`
    font-size: 1.4rem;
`
每种标准款式都可能有不同的款式。G标准的粗体段落。我想知道实现这一目标的最佳方式是什么。我可以看到几种方法:

方式1(传递粗体道具):

const P = styled.p`
    font-weight: ${({fontWeight}) => fontWeight ? fontWeight : 'normal'}
`
export const BoldP = props => <P fontWeight="bold">
export const P = styled.p`
    font-weight: ${({fontWeight}) => fontWeight ? fontWeight : 'normal'}
`

export const BoldP = styled(P)`
    font-weight: bold
`
方式2(创建具有粗体道具的组件,但导出已具有道具的单独组件):

const P = styled.p`
    font-weight: ${({fontWeight}) => fontWeight ? fontWeight : 'normal'}
`
export const BoldP = props => <P fontWeight="bold">
export const P = styled.p`
    font-weight: ${({fontWeight}) => fontWeight ? fontWeight : 'normal'}
`

export const BoldP = styled(P)`
    font-weight: bold
`

这个问题可能看起来有点亵渎,但由于这是许多应用程序的标准界面,我想知道是否有一种“正确”的方法来做到这一点。

如果你需要一些标准的共享值,如主站点颜色,那么你需要全局样式的主题组件

首先创建全局主题上下文:

import React, { useEffect, useState } from 'react'
import { deepClone } from '@shared'
import { defaultGeneralTheme } from '../data/defaultGeneralTheme'
import { ThemeProvider, createGlobalStyle } from 'styled-components'

export const ThemeContext = React.createContext(null)

export const ThemeContextProvider = props => {
  const [generalTheme, setGeneralTheme] = useStateRo(deepClone(defaultGeneralTheme))

  return (
    <ThemeContext.Provider value={{ generalTheme, setGeneralTheme }}>
      <ThemeProvider theme={theme}>
        <>
          <GlobalStyle />
          {props.children}
        </>
      </ThemeProvider>
    </ThemeContext.Provider>
  )
}

const GlobalStyle = createGlobalStyle`
  body {  
    line-height: 1.2rem;
    background-color:  ${({ theme }) => theme.secondaryColor};
  } 
`
别忘了用提供程序包装顶级组件:

<ThemeContextProvider><App /></ThemeContextProvider>