Styled-JSX变量不生效求助:动态样式无法正常应用
Hey there, let's walk through the issues in your code that are causing the styles not to apply—even though your state is updating correctly, there are a few syntax mistakes breaking the styled-jsx functionality:
Component definition mix-up: You’ve got the order wrong when exporting your component. It should be
export default class Index extends Componentinstead ofexport default Index class extends Component—the class name needs to come right after theclasskeyword.Invalid return statement in render: Your
render()method usesreturn(){which is invalid syntax. You should wrap your JSX in parentheses likereturn (instead.Unclosed
setStatecall: In your button’sonClickhandler, you’re missing a closing parenthesis forsetState. The correct line is:onClick={() => this.setState({clicked: !this.state.clicked})}You had an extra closing curly brace instead of closing the
setStatefunction call.Broken style tag closing: You tried to close the
<style jsx>tag with another<style>instead of</style>—this syntax error stops styled-jsx from parsing your styles properly.Missing semicolon in CSS: Your
background-colordeclaration doesn’t end with a semicolon, which can cause CSS parsing issues in styled-jsx. Always add semicolons to your CSS rules!
Here's the fixed version of your component:
import React, { Component } from 'react' export default class Index extends Component { constructor(props){ super(props) this.state = { clicked: false} } render(){ return( <div> <button onClick={() => this.setState({clicked: !this.state.clicked})}>Hello</button> <style jsx>{` button { background-color: ${this.state.clicked ? 'red' : 'blue'}; } `}</style> </div> ) } }
内容的提问来源于stack exchange,提问作者Taylor Austin

