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