On Github chentsulin / radium-intro
在 vjeux 的 react css in js 中有提到:
全域的命名空間 (global namespace) 相依性 (dependencies) 沒用到的程式碼 (dead code) 壓縮 (minification) CSS 跟 JS 共用常數 (sharing constants) 不確定性的解析 (non-deterministic resolution) 沒有隔離性 (isolation)Inline style 則可以改善這些問題
先 import
var Radium = require('radium');
// or
import Radium from 'radium';
然後就可以用 ES7 decorator 去裝飾 React Component
@Radium
class Button extends React.Component {
// ...
}
export default Button;
也可以不用 decorator
class Button extends React.Component {
// ...
}
export default Radium(Button);
這樣裝飾過的 React Component,就會有 Radium 延伸的功能
可以使用 array 來作為 style
@Radium
class Button extends React.Component {
render() {
return (
<button
style={[
styles.base,
this.props.style
]}>
{this.props.children}
</button>
);
}
}
後面的 style 會蓋掉前面 style 的屬性,就像 Object.assgin 一樣
或是用 props 來變動幾種樣式
render() {
return (
<button
style={[
styles.base,
styles[this.props.kind]
]}>
{this.props.children}
</button>
);
}
或是用 truthy, falsy 值來決定樣式
render() {
return (
<button
style={[
styles.base,
this.props.block && styles.block
]}>
{this.props.children}
</button>
);
}
Radium 會忽略所有不是 object 的元素
radium 支援 :hover :focus :active 這三個瀏覽器狀態 pseudo-selector
可以作為屬性再設定 style object:
var styles = {
base: {
background: 'blue',
color: 'white',
':hover': {
backgroundColor: 'red'
},
':focus': {
backgroundColor: 'green'
},
':active': {
backgroundColor: 'yellow'
}
}
}
Media queries
可以作為屬性再設定 style object:
var style = {
width: '25%',
'@media (min-width: 320px)': {
width: '100%'
}
};
使用 Keyframes
用 Radium.keyframes:
var pulseKeyframes = Radium.keyframes({
'0%': {width: '10%'},
'50%': {width: '50%'},
'100%': {width: '10%'},
});
var styles = {
inner: {
animation: `${pulseKeyframes} 3s ease 0s infinite`,
background: 'blue',
height: '4px',
margin: '0 auto',
}
};
就需要用到 getState 這個方法
Radium.getState(state, elementKey, value):boolean
state:通常會傳入 this.state,不過也有可能會傳入之前的 state
elementKey:如果有多個元素必須傳 key="" 或是 ref="" 的值,如果只有一個元素則可以留空
value::active :focus :hover 其中一個
return:回傳布林值
Thanks for listening