【问题标题】:How can I access themeprovider/styled-components styles from render in React/NextJS如何从 React/NextJS 中的渲染访问 themeprovider/styled-components 样式
【发布时间】:2021-02-06 19:17:26
【问题描述】:

我的代码设置是这样工作的......

_app.js

<ThemeProvider theme={clientGroupTheme}>
    <GlobalStyles />
    <Layout>
      <Component {...this.props} />
    </Layout>
</ThemeProvider>

someComponent.js

import { createGlobalStyle } from 'styled-components'
export const LoginMenuStyles = createGlobalStyle`
    .exampleClass {
         color:${(props) => props.theme.secondaryColor};
    }`

class LoginMenu extends React.Component {
    render() {
        return ( <>
                <div className="exampleClass">Test</div>
                <PassColorComponent myColor={${(props) => props.theme.secondaryColor}} /> //This
            </>
        )
    }
}

基本上我想传递相同的颜色值作为道具 (//This)。它在 styled-component 类中工作正常,但我可以让它在 render 方法中工作并传递给该组件。 可能吗?我很亲密吗? 谢谢

【问题讨论】:

标签: reactjs next.js styled-components


【解决方案1】:

创建样式组件时,主题仅在styled 函数中可用。如果你想在 React 组件 中访问,你可以例如直接将主题作为道具传递下去。

<Component {...this.props} theme={clientGroupTheme} />

然后,您将能够访问 主题 对象。

<PassColorComponent myColor={props.theme.secondaryColor} />

【讨论】:

    【解决方案2】:

    我认为 'withTheme' 高阶组件是您正在寻找的。​​p>

    import { withTheme } from 'styled-components'
    
    
    class LoginMenu extends React.Component {
        render() {
            return ( <>
                    <div className="exampleClass">Test</div>
                    <PassColorComponent myColor={this.props.theme.secondaryColor} />
                </>
            )
        }
    }
    
    export default withTheme(LoginMenu);
    

    不要忘记将导出时的组件包装在 withTheme 组件内(见底线)。这就是样式化主题道具将如何传递给 LoginMenu 组件的方式。

    【讨论】:

    • 你能解释一下如何使用这样的功能组件:export default function LoginMenu (props) {
    • @Thomas Byy import {withTheme} from 'styled-components'; function Component(props){ console.log(props.theme) // component structure here } export default withTheme(Component)
    猜你喜欢
    • 2021-07-16
    • 2020-01-08
    • 2021-08-26
    • 2017-07-20
    • 2021-03-15
    • 2021-09-19
    • 2018-10-20
    • 1970-01-01
    • 2019-12-21
    相关资源
    最近更新 更多