繁体   English   中英

在 react 组件中使用 styled-jsx

[英]Use styled-jsx in react component

我正在尝试在 react 组件(使用 create react app 创建)中使用 styled-jsx 库。

但我得到了错误:

styled-jsx/css:如果您收到此错误,则表示您的css标记模板文字没有被转译。

我不确定如何解决它,或者无法使用这个用于反应组件的库(这是我第一次使用它)。

import React from 'react';
import css from 'styled-jsx/css'
// import './styles';

export default function MyComponent(props) {
    return (
        <>
            <div key={props.value}>{props.label}</div>
            <style jsx>{button}</style>
        </>
    )
}

const button = css`div { color: hotpink; }`

非常感谢!

您需要按照这些说明安装 babel 插件。

  1. 在 babel-loader 之前运行 styled-jsx/webpack
  2. 将 styled-jsx/babel 添加到 babel 加载器插件

该错误并不表明您的标记存在问题,更多的是代码是如何被转译的,但您可以通过简化它来进行测试:

import React from 'react';
import css from 'styled-jsx/css'

export default function MyComponent(props) {
    return (
        <>
            <div key={props.value}>{props.label}</div>
            <button>Click Me</button>

            <style jsx>{`
              button {
                color: hotpink;
              }
`            `}</style>
        </>
    )
}

使用 Vite 安装 React,可以访问所有配置
vite.config.js 这是我的工作配置:记得重启开发脚本。

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react({
      babel: {
        parserOpts: {
          "plugins": ["styled-jsx/babel"]
        }
      }
    })
  ]
})

编辑:这是一个关于如何在 Create-React-App CRA 中执行此操作的链接 - 使用 Styled JSX

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM