简体   繁体   English

使用 styled-jsx,如何在存储在变量中的 JSX 上使用样式?

[英]Using styled-jsx, how can I use styles on JSX stored in a variable?

I am using a variable to conditionally show different JSX and it isn't using the styling that is defined in its parent function.我正在使用一个变量来有条件地显示不同的 JSX,它没有使用在其父函数中定义的样式。 How can I make that work?我怎样才能做到这一点?

You can see a demo here: https://codesandbox.io/s/styled-jsx-example-e6tf6你可以在这里看到一个演示: https : //codesandbox.io/s/styled-jsx-example-e6tf6

import React from 'react'

function StyledJsxTest({ isLoggedIn, areButtonsVisible }) {
  function renderButtons() {
    const buttons = isLoggedIn ? (
      <a className="button" href="/dashboard">Dashboard</a>
    ) : (
      <>
        <a className="button" href="/signIn">Log In</a>
      </>
    )

    return (
      <div>
        <div>
          <a className="button" href="/dashboard">Test</a>
          {buttons}
        </div>
        <style jsx>{`
          .button {
            background-color: blue;
            color: white;
            padding: 20px;
            margin: 10px;
          }
        `}
        </style>
      </div>
    )
  }

  return (
    <div>
      <h1>This is a headline</h1>
      {renderButtons()}
    </div>
  )
}

export default StyledJsxTest

The buttons in this chunk of code are not getting the . button这段代码中的按钮没有得到. button . button rule. . button规则。 How can i get those to work?我怎样才能让这些工作?

const buttons = isLoggedIn ? (
      <a className="button" href="/dashboard">Dashboard</a>
    ) : (
      <>
        <a className="button" href="/signIn">Log In</a>
      </>
    )

My guess would be that you forgot to add styled-jsx/babel to your .babelrc configuration .我的猜测是您忘记将styled-jsx/babel添加到您的.babelrc配置中

在此处输入图片说明

Working example :工作示例

编辑包裹反应模板

I think the following should do what you're after:我认为以下应该做你所追求的:

import React from 'react'

function Button(props) {
  return (
    <a 
      {...props} 
      style={{
        backgroundColor: 'blue',
        color: 'white',
        padding: '20px',
        margin: '10px'
      }}
    >
      {props.children}
    </a>
  );
}

function StyledJsxTest({ isLoggedIn, areButtonsVisible }) {
  return (
    <div>
      <h1>This is a headline</h1>
      <div>
        <Button className="button" href="/dashboard">Test</Button>
        {isLoggedIn ? 
          <Button className="button" href="/dashboard">Dashboard</Button>
          : 
          <Button className="button" href="/signIn">Log In</Button>
        }
      </div>
    </div>
  )
}

export default StyledJsxTest

Actually, I think there is no problem running the code and getting the style of .button class.实际上,我认为运行代码并获取 .button 类的样式没有问题。
However, I might write it somehow different;但是,我可能会以某种不同的方式写它; but, it works !但是,它有效!
The problem maybe of your browser cache可能是浏览器缓存的问题
我对你的风格做了一些小小的改变,它奏效了 or something !或者其他的东西 !

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM