React:Css module:自动生成className

本文介绍了如何在React项目中使用CSS Module来自动生成不重复的className。通过修改webpack配置,在css options中启用module选项。在最新的React版本中,只需将CSS文件命名为name.module.css。示例中展示了在App.js和Person.js组件中应用CSS Module的两种写法,以及如何使用`:global`修饰符来定义全局样式。
摘要由CSDN通过智能技术生成

change configuration

npm run eject

得到config文件并可修改;

进入webpack.config.dev.js

在css options中增加

modules:true
localIdentName:'[name]__[local]__[hash:base64:5]'

module可为css自动创建不重复的class;

最新的react无需手动修改

将css文件命名为 name.module.css即可;

App.js

import React, { Component } from 'react';
import Cssclasses from './App.module.css';
import Person from './Person/person';


class App extends Component{
  state={
    persons:[
      {id:'asfa1', name:'Max' , age:28},
      {id:'asfa2', name:'manu' , age:24},
      {id:'asfa3', name:'Snie' , age:26}
    ],
    isshow:false
  };

  clicktoshow =(event)=>{
    const tmp = this.state.isshow;
    this.setState({isshow:!tmp});
  }

  deletePersonHandler=(personIndex)=>{
    // const persons = this.state.persons.slice();  //返回一个copy
    const persons = [...this.state.persons];  //内容复制
    persons.splice(personIndex,1);
    this.setState({persons:persons});
  }


  nameChangedHandler = (event,id)=>{
    const personIndex = this.state.persons.findIndex(p=>p.id===id);
    const person = {
      ...this.state.persons[personIndex]
    };
    person.name=event.target.value;
    const persons=[...this.state.persons];
    persons[personIndex]=person;
    this.setState({persons:persons});
  }

  render(){
  let person=null;
  let btnClass=[Cssclasses.Button];     //一个指向特殊名字的指针



  if(this.state.isshow){
    person=(
      <div>
        {
          this.state.persons.map((person,index)=>{
            return <Person 
                    name={person.name}
                    age={person.age}
                    click={this.deletePersonHandler.bind(this,index)}
                    key={person.id}
                    changed={(event)=>this.nameChangedHandler(event,person.id)}
                    />
          })
        }
      </div>
    );
    btnClass.push(Cssclasses.Red);
  }

  


  const classes=[];
  if(this.state.persons.length<=2){
    classes.push(Cssclasses.red); //classes =['red']
  }
  if(this.state.persons.length<=1){
    classes.push(Cssclasses.bold); //classes =['red','bold']
  }


  return (

      <div className={Cssclasses.App}>
        <h1>Hi i am a React App!</h1>
        <p className={classes.join(' ')}>It is working!</p>
        <button       
        className={btnClass.join(' ')}
        onClick={this.clicktoshow}>Switch name
        </button>
        {person}
      </div>

  );};
}

export default App;

App.module.css

.App {
  text-align: center;
}


.red{
  color:red;
}


.bold{
  font-weight: bold;
}


.Button{
  background-color:green;
  color:white;
  font:inherit;
  border:1px solid blue;
  padding:8px;
  cursor:pointer;


}  
.Button:hover{
    background-color:lightgreen;
    color:black;
  }

.Button.Red{
  background-color:red;
}

.Button.Red:hover{
  background-color:salmon;
}

写法2:对App类设置style

App.js

import React, { Component } from 'react';
import Cssclasses from './App.module.css';
import Person from './Person/person';


class App extends Component{
  state={
    persons:[
      {id:'asfa1', name:'Max' , age:28},
      {id:'asfa2', name:'manu' , age:24},
      {id:'asfa3', name:'Snie' , age:26}
    ],
    isshow:false
  };

  clicktoshow =(event)=>{
    const tmp = this.state.isshow;
    this.setState({isshow:!tmp});
  }

  deletePersonHandler=(personIndex)=>{
    // const persons = this.state.persons.slice();  //返回一个copy
    const persons = [...this.state.persons];  //内容复制
    persons.splice(personIndex,1);
    this.setState({persons:persons});
  }


  nameChangedHandler = (event,id)=>{
    const personIndex = this.state.persons.findIndex(p=>p.id===id);
    const person = {
      ...this.state.persons[personIndex]
    };
    person.name=event.target.value;
    const persons=[...this.state.persons];
    persons[personIndex]=person;
    this.setState({persons:persons});
  }

  render(){
  let person=null;
  let btnClass='';     //一个指向特殊名字的指针



  if(this.state.isshow){
    person=(
      <div>
        {
          this.state.persons.map((person,index)=>{
            return <Person 
                    name={person.name}
                    age={person.age}
                    click={this.deletePersonHandler.bind(this,index)}
                    key={person.id}
                    changed={(event)=>this.nameChangedHandler(event,person.id)}
                    />
          })
        }
      </div>
    );
    btnClass=Cssclasses.Red;
  }

  


  const classes=[];
  if(this.state.persons.length<=2){
    classes.push(Cssclasses.red); //classes =['red']
  }
  if(this.state.persons.length<=1){
    classes.push(Cssclasses.bold); //classes =['red','bold']
  }


  return (

      <div className={Cssclasses.App}>
        <h1>Hi i am a React App!</h1>
        <p className={classes.join(' ')}>It is working!</p>
        <button       
        className={btnClass}
        onClick={this.clicktoshow}>Switch name
        </button>
        {person}
      </div>

  );};
}

export default App;

App.module.css

.App {
  text-align: center;
}


.red{
  color:red;
}


.bold{
  font-weight: bold;
}


.App button{
  background-color:green;
  color:white;
  font:inherit;
  border:1px solid blue;
  padding:8px;
  cursor:pointer;


}  
.App button:hover{
    background-color:lightgreen;
    color:black;
  }

  .App button.Red{
  background-color:red;
}

.App button.Red:hover{
  background-color:salmon;
}


Person.js

import React from 'react';
// import './Person.css';
import classes from './person.module.css';


const person = (props)=>{


  return(
    // <div className="Person" style={style}> 
    <div className={classes.Person}>
      <p>I Am a person!</p>
      <p onClick = {props.click}>{props.name}</p>
      <p>i'm {props.age}</p>
      <p>{props.children}</p>
      <input type="text" onChange={props.changed} value={props.name}/>
    </div>
  )
};

export default person;

Person.module.css

.Person{
  margin: 16px auto;
  color: rgb(73, 54, 47);
  width: 60%;
  border: 1px solid #eeeeee;
  box-shadow:0 2px 3px rgb(208, 214, 214);
  padding: 16px;
  text-align: center;
}

@media (min-width: 500px){
  .Person{
    width: 450px;
  }
}

:global .Post{}

则post可被直接作为 className=“Post”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值