• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
逍遥汉
博客园    首页    新随笔    联系   管理    订阅  订阅

nextJs中使用styled-jsx

NextJs 不支持直接在页面和组件里import Css这种引入方式(除了全局引入),但是可以使用styled-jsx的方式进行Css的样式定义,也可以实现样式加载

NextJs中Css的几种使用方案:

  •  global 全局引入: 在main文件或者app.js/ts 文件里面进行全局引入,这种只是适合全局作用的样式引入。例如: import './index.css'。
  • css module 引入:这种一般来说适用于页面或者组件的引入方式,可以有效解决css命名冲突的问题;例如:import styles from './index.module.scss'。
  • nextJs还支持tailWindCss,这种比较方便直接,取决于项目有没有配置相关的东西;
  • 最后一种也是现在项目包括各种组件库常用的解决方案;css-in-js,这种其实通过在jsx中定义css,可以0成本使用js中的变量,比较方便,解决import后,变量命名的冲突问题,感觉和vue的scope有点类似。styled-jsx也是Css-in-js的一种,
  • styled-components也是其中一种解决方案

全局Style

<style global jsx>{`
  .hero {
    width: 100%;
    color: #333;
  }
  .title {
    margin: 0;
    width: 100%;
    padding-top: 80px;
    line-height: 1.15;
    font-size: 48px;
  }
   button {
    background: red;
  }
`}</style>

global(只针对某个 css 全局)

export default () => (
  <div>
    <Select optionClassName="react-select" />
 
    <style jsx>{`
      /* "div" will be prefixed, but ".react-select" won't */
 
      div :global(.react-select) {
        color: red
      }
    `}</style>
  </div>

行内 sytle

const Button = ({ padding, children }) => (
  <button style={{ padding }}>
     { children }
     <style jsx>{`
        button {
          padding: 20px;
          background: #eee;
          color: #999
        }
     `}</style>
  </button>
)
<div className="root">
    <style jsx>{`
      .root {
        color: green;
      }
    `}</style>
  </div>

className 切换

const Button = (props) => (
  <button className={ 'large' in props && 'large' }>
     { props.children }
     <style jsx>{`
        button {
          padding: 20px;
          background: #eee;
          color: #999
        }
        .large {
          padding: 50px
        }
     `}</style>
  </button>
)

 

时间如白驹过隙,忽然而已,且行且珍惜......
posted @ 2024-04-11 11:35  unfetteredman  阅读(286)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3