【发布时间】:2021-04-29 07:27:18
【问题描述】:
我正在尝试更改body 上的transition,具体取决于页面是否已加载或是否单击了ThemeToggle 按钮。但我看不到向GlobalStyles发送道具的方法
App.tsx
import React, { ReactElement } from 'react'
import { createGlobalStyle } from 'styled-components'
import { Theme } from '@components/Theme/'
interface IPalette {
body: string
text: string
}
const GlobalStyles = createGlobalStyle<{ theme: IPalette }>`
body {
background: ${({ theme }) => theme.body};
color: ${({ theme }) => theme.text};
/* I want to modify the transition on load */
transition: background-color 0.3s ease;
}
`
export const App = (): ReactElement => {
return (
<Theme>
<GlobalStyles />
<h1>Test</h1>
</Theme>
)
}
主题.tsx
import React, { FC, useState, useEffect } from 'react'
import { ThemeProvider } from 'styled-components'
import { darkTheme, lightTheme, ThemeToggle } from './theme-style'
import { createCookie, eraseCookie, readCookie } from './cookie'
export const Theme: FC<{children: React.ReactNode}> = ({children}) => {
const [themeState, setTheme] = useState<boolean>(false)
const [firstLoad, setFirstLoad] = useState<boolean>(true)
const changeTheme = (): void => {
setFirstLoad(false)
if (themeState) {
setTheme(false)
eraseCookie('Theme')
} else {
setTheme(true)
createCookie('Theme', true, 30)
}
}
useEffect(() => {
if (readCookie('Theme')) setTheme(true)
}, [])
return (
<ThemeProvider theme={themeState ? darkTheme : lightTheme}>
{children}
<ThemeToggle theme={themeState} onClick={changeTheme} />
</ThemeProvider>
)
}
我正在尝试将 firstLoad 布尔值从 ThemeProvider 发送到 GlobalStyles,但如果我尝试,我会收到来自 TypeScript 的错误。
Type '{ children: (ReactNode | Element)[]; firstLoad: true; theme: IPalette; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemeProviderProps<any, any>, any, any>> & Readonly<...> & Readonly<...>'.
【问题讨论】:
标签: reactjs typescript styled-components