0
点赞
收藏
分享

微信扫一扫

React之样式 ( 3 )

上善若水的道 2022-03-15 阅读 69

内联样式

  1. 内联需要放到 { } 中
  2. 内联无法支持伪类及媒体查询
  3. 使用 radium 插件可以提供支持
    1. 导入 Radium 后包裹组件之后再导出 import Radium from ‘radium’ (支持伪类 && 条件样式)
    2. 导入 styleRoot 后,在渲染组件的地方再次包裹 (支持媒体查询)

例子

function App() {
  return (
    <div style={{ height: "100px", background: "orange" }}>
      that div happy
    </div>
  );
}
const divStyle = {
  height: 200,
  background: "orange"
}

function App() {
  return (
    <div style={ divStyle }>
      that div happy
    </div>
  );
}
app.js 中
import Radium from "radium";

const divStyle = {
  base: {
    height: 200,
    background: "orange",
    ":hover": { background: "red" },
    "@media(max-width:1500px)": { width: 100 }
  },
  inStyle: { fontSize: 20  },
  outStyle: { color: "white" }
}

const flag = true

function App() {
  return (
    <div style={ [ divStyle.base, flag ? divStyle.inStyle : divStyle.outStyle ] }>
      that div happy
    </div>
  );
}

export default Radium(App);

index.js 中
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { StyleRoot } from 'radium'

ReactDOM.render(
  <React.StrictMode>
    <StyleRoot>
    <App />
    </StyleRoot>
  </React.StrictMode>,
  document.getElementById('root')
);

外联样式

定义全局样式

在这里插入图片描述
引入
在这里插入图片描述
使用

在这里插入图片描述

组件样式

定义
在这里插入图片描述
使用
在这里插入图片描述

独立使用

import Radium from "radium";
import styled from 'styled-components'

const CustomDiv = styled.div`
  width: 100px;
  height: 100px;
  background: orange;
`

// 设置属性
const CustomDivAttr = styled.div.attrs({
  className: "div-style1 div-style2"
})`
  width: 100px;
  height: 100px;
  background: red;
`

function App() {
  return (
    <div>
      <CustomDiv>内容1</CustomDiv>
      <CustomDivAttr>内容2</CustomDivAttr>
    </div>
  );
}

export default Radium(App);
举报

相关推荐

0 条评论