You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Component instead of export default Index class extends Component—the class name needs to come right after the class keyword.

  • Invalid return statement in render: Your render() method uses return(){ which is invalid syntax. You should wrap your JSX in parentheses like return ( instead.

  • Unclosed setState call: In your button’s onClick handler, you’re missing a closing parenthesis for setState. The correct line is:

    onClick={() => this.setState({clicked: !this.state.clicked})}
    

    You had an extra closing curly brace instead of closing the setState function 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-color declaration 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:43:08