react中使用css的方式
在react中使用css有两种主要的方法:内联样式和外部样式表。
1. 内联样式
import React from 'react'
interface Props{
className?:string
}
const styles = {
container:{
display:flex,
justifyContent:'center'
},
button:{
padding:'10px 20px',
fontSize:'16px'
}
}
const ButtonComponent:React.Fc<Props> = (
return (
<div style={styles.container}>
<button style={styles.button} className={className}>click me!</button>
</div>
)
)
上面的例子中定义了两个对象:container和button。这些样式对象包含了css属性和值,可以直接应用于组件的jsx中。
2. 外部样式表
使用外部样式表是一种常见的做法,可以在react+typescript项目中使用模块或者普通的css文件。
模块
styles.module.css
.container{
display:flex;
height:100vh;
}
.button{
padding: 10px 20px;
border: none;
}
ButtonComponent.tsx
import React from 'react'
import styles from './styles.module.css' // 导入css模块
interface Props {
className?:string
}
const ButtonComponent: React.FC<props> = ((className))=>{
return (
<div className={styles.container}>
<button className={`${style.button} ${className}`}>click me!</button>
</div>
)
}
export default ButtonComponent
上面的例子中我们定义了一个名为styles.module.css的css模块文件,并在ButtonComponent组件中导入它,这样,我们可以使用模块中的类名来应用样式。
使用普通的css文件
如果使用的是普通的css文件而不是css模块,你可以直接在HTML中使用类名,或者使用css-in-js库(styled-components或emotion)来动态生成样式。
styles.css
.container{
padding: 10px;
display:flex;
border:none;
}
.button{
padding:10px 20px;
font-size: 20px;
border:none;
}
ButtonComponent.tsx
import React from 'react'
import './style.css'
interface Props{
className?:string
}
const ButtonComponent:React.FC<Props>=((className))=>{
return (
<div className="container">
<button className={button ${className}}></button>
</div>
)
}
export default ButtonComponent
在上面的例子中,直接导入了普通的css文件,并在jsx中使用了类名来应用样式。
总结
- 内联样式
适应于简单的样式和动态计算样式的情况 - css模块 使用于避免类名冲突的场景
- 普通css文件 适用于静态样式,通常用于全局样式和多个组件共享的样式