内联样式
- 内联需要放到 { } 中
- 内联无法支持伪类及媒体查询
- 使用 radium 插件可以提供支持
- 导入 Radium 后包裹组件之后再导出 import Radium from ‘radium’ (支持伪类 && 条件样式)
- 导入 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);