nextjs样式的定义
1.nextjs默认是不支持去加载一个css文件的,需要通过修改配置实现;
2.默认集成使用css-in-js方案,在nextjs当中默认使用styled-jsx 形成一个编译之后的className,组件间隔离,不影响其他组件的样式;
3.nextjs已集成好自动做好服务端渲染,即服务端渲染直接返回有样式的内容,不需要等到客户端渲染时渲染样式
1.增加组件内的样式 内部使用javascript字符串模板
2.增加全局的样式
效果
3.动态修改样式
nextjs集成styled-components
集成步骤
上文为nextjs默认集成的styled-jsx的css-in-js方案
集成其他的第三方的css-in-js方案——使用styled-component
yarn add styled-components babel-plugin-styled-components //预编译css
第一步:.babelrc
第二步:_document.js
originalRenderPage方法通过对APP增强的方式来将使用的第三方库能够在服务器端渲染的时间段去执行一些代码来进行一个服务端渲染的集成的过程
sheet.collectStyles将样式挂载到组件中
sheet.getStyleElement() 拿到样式效果
使用:
效果:
styled-components优势
正如styled-components的联合创始人 Max Stoiber 所说:
“styled-components的最基本思想就是通过移除样式和组件之间的映射来执行最佳实践”
例子
const Title = styled.h1`
font-size: 1.5em;
color: ${props => props.primary ? 'blue' : 'purple'};
`;
<Title primary>Hello World</Title> // will be blue
const Title = styled.h1`
font-size: 1.5em;
color: purple;
&.primary{
color: blue;
}
`;
<Title className="primary">Hello World</Title> // will be blue
1、styled-components通过封装所有CSS和HTML相关的实现细节来让组件更加干净。
2、样式可以使用变量,更加灵活,可复用。
3、使用方便,不需要配置 webpack、开箱即用。
4、SSR 类框架处理 CSS Modules 变量相当棘手,所以使用 styled-components 作方案
未完待续~