开发者社区> 问答> 正文

使用样式-jsx,我如何使用储存在变量的jsx样式?

我使用一个变量来有条件地显示不同的JSX,它没有使用在其父函数中定义的样式。我怎样才能做到这一点?

您可以在这里看到一个演示: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

这段代码中的按钮没有得到js .button 规
则。我怎样才能让它们发挥作用?

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

展开
收起
sossssss 2019-12-09 15:59:20 878 0
0 条回答
写回答
取消 提交回答
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载