【问题标题】:Styled-JSX variables not workingStyled-JSX 变量不起作用
【发布时间】:2018-10-20 01:25:00
【问题描述】:

我已经使用styled-jsx@2.2.6 安装了 styled-jsx,并且正在做类似的事情:

import React, { Component } from 'react'

export default Index class 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>
  }
 }
}

没有任何样式被应用,我在控制台中注销了单击状态并且它正在被更改。

【问题讨论】:

  • 您是否将 styled-jsx 添加到您的 babel 插件中?
  • 我正在使用 gatsby。它有一个gatsby-plugin-styled-jsx,位于gatsby-config 中。我还没有在 .babelrc 中这样做,我该怎么做呢?
  • { "插件": [ "styled-jsx/babel" ] }
  • 现在我收到Uncaught SyntaxError: Unexpected identifier的错误
  • 这个错误是在哪个过程中出现的,你能发布整个输出吗?

标签: reactjs styles jsx styled-components


【解决方案1】:

这是一个工作示例。你那里有很多错字。我假设您没有使用通常会指出所有这些问题的适当 IDE。

这是工作代码:https://stackblitz.com/edit/react-3ttfch

这是您固定的无打字错误代码:

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>
    );
  }
}

【讨论】:

  • 我需要在 styled-jsx 中添加一个插件,这样我才能使用嵌套。我尝试在 babelrc 中这样做:["styled-jsx/babel", { "plugins": ["styled-jsx-plugin-postcss"] }] 但我只是在控制台中得到Uncaught SyntaxError: Unexpected identifier
  • 假设您的代码符合 JS 语法,这些都是在构建过程中使用的所有插件。在您的情况下,情况并非如此,正如我所说,您的错别字太多。您可以单击上面提供的链接并查看它是否正常工作。它的代码与您刚刚没有语法错误的代码相同。
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 2020-12-26
  • 2019-10-09
  • 2019-07-11
  • 2021-02-28
  • 1970-01-01
  • 2023-01-16
  • 2019-07-28
相关资源
最近更新 更多