next styled-jsx教程 react中使用styled-jsx

本文介绍了一个用于编写CSS-in-JS的插件styled-jsx。它包括安装步骤和使用方法,如组件内样式和全局样式定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

styled-jsx

styled-jsx是一个支持jsx方式编写的css-in-js插件

01.安装

1.用npm安装styled-jsx

npm install --save styled-jsx

2.在babelplugins中配置styled-jsx/babe

{
  "plugins": [
    "styled-jsx/babel"
  ]
}

如果用了next.js不用写上面的配置, 因为next.js中已经默认引入了styled-jsx插件

02. 如何使用

组件内样式

<style jsx>中编写你的css代码

export default () => (
  <div>
    <p>only this paragraph will get the style :)</p>
    <style jsx>{`
      p {
        color: red;
      }
    `}</style>
  </div>
)

公共样式

使用css.global定义全局样式

1.编写公共样式文件

/* global.js */
import css from 'styled-jsx/css'

export const globalStyle = css.global`
body {
  margin: 0;
  background-color: AntiqueWhite;
}
button {
  color: green;
}
`

2.在父组件中引入全局样式文件并应用

/* index.js */
//1.引入
import { globalStyle} from '../src/styles/global.js';

class MyApp extends App {
	public render() {
		return (
		<div>
			//2.引用
			<style jsx={true} global={true}>{globalStyle}</style>
		</div>
		)
	}
}

styled-jsx还有很多很牛的功能, 但是我也是初学者, 只有英文文档只能看懂一点.有写得不好的地方希望大家多多指正.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值