styled-jsx使用
styled-jsx
styled-jsx是一个支持jsx方式编写的css-in-js插件
01.安装
1.用npm安装styled-jsx
npm install --save styled-jsx
2.在babel
的plugins
中配置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还有很多很牛的功能, 但是我也是初学者, 只有英文文档只能看懂一点.有写得不好的地方希望大家多多指正.