React style/css样式 styling components

Styling react components & elements
Setting styles dynamically 动态改变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是包装在相应的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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。