Styling react components & elements
Setting styles dynamically 動態(tài)改變css
(Radium)--支持:hover和media queries
(styled component)--支持:hover和media queries( regular css)
1.用html style屬性時:js在處理變化的時候同時改變style值
2.用className:
- 常用push
const classes=[]
if(this.state.persons.length <= 2){
classes.push('red');
}
if(this.state.persons.length <= 1){
classes.push('bold');
}
...
<div className={classes.join(' ')}></div>
Radium
- using Radium
npm install --save radium
import Radium from 'radium'
render(){
const style={
backgroundColor:'#ccc';
font:'inherit';
border:'1px solid blue;
cursor:'pointer'
':hover':{
background:'lightgreen',
color:'black'
}
};
if(this.state.show){
...
style[':hover']={
background:'salmon',
color:'black'
}
}
return(<div>
<button style={style}></button>
</div>)
}
export default radium(App);
- using Radium for media queries
import Radium,{StyleRoot} from 'radium'
const style={
'@media (min-width:500px):{
width:500px;
}
}
...
<StyleRoot>
<div style={style}>
...
</div>
</StyleRoot>//這個需要包裝在整個app之外,而包裝class的radium是包裝在相應(yīng)的class外
...
export default radium(App);
- styled component library
remove all radium /
import styled from 'styled-components'
const StyledDiv = styled.div``//!Upper case start
width:60%;
margin:16px auto;
border:1px solid #eee;
@media (min-width:500px){
.Person{
width:450px;
}
}
...
return(
<StyledDiv></StyledDiv>
)
- styled component & dynamic style
import styled from 'styled-components'
const StyledDiv = styled.div``//!Upper case start
background-color:${props=>props.alt?'red':'blue';
width:60%;
margin:16px auto;
border:1px solid #eee;
@media (min-width:500px){
.Person{
width:450px;
}
}
...
return(
<StyledDiv alt={this.state.show} onClick={...}></StyledDiv>
)
- CSS Modules
/* style.css */
.className {
color: green;
}
...
import styles from "./style.css";
// import { className } from "./style.css";
element.innerHTML = '<div class="' + styles.className + '">';
In Post.css File
1. .Post {
2. color: red;
3. }
In Post Component File
1. import classes from './Post.css';
3. const post = () => (
4. <div className={classes.Post}>...</div>
5. );
Here, classes.Post
refers to an automatically generated Post
property on the imported classes
object. That property will in the end simply hold a value like Post__Post__ah5_1
.
CSS Modules are a relatively new concept (you can dive super-deep into them here: https://github.com/css-modules/css-modules).
Link
- Using CSS Modules in create-react-app Projects: https://medium.com/nulogy/how-to-use-css-modules-with-create-react-app-9e44bec2b5c2
- More information about CSS Modules: https://github.com/css-modules/css-modules