JavaScript教程:React中使用css样式的5种方式

react中的样式方法
1. 行内样式
class App extends React.Component { // ... render() { return ( <div style={{ background: '#eee', width: '200px', height: '200px'}}> <p style= {{color:'red', fontSize:'40px'}}>行内样式</p> </div> ) } }
2.声明样式
class App extends React.Component { //... const style1={ background:'#eee', width:'200px', height:'200px' } const style2={ color:'red', fontSize:'40px' } render() { return ( <div style={style1}> <p style= {style2}>行内样式</p> </div> ) } }
3. 引入样式
// css .person{ width: 60%; margin:16px auto; border: 1px solid #eee; box-shadow: 0 2px 3px #ccc; padding:16px; text-align: center; } // js import React from 'react'; import './Person.css'; class App extends React.Component { //.... render() { return ( <div className='person'> <p>person:Hello world</p> </div> ) } } export default App;
4.CSS Modules
// xxx.module.css .person{ width: 60%; margin:16px auto; border: 1px solid #eee; box-shadow: 0 2px 3px #ccc; padding:16px; text-align: center; } // js import React, { Component } from 'react'; //局部样式 import styles from './Person.module.css'; //全局样式 import '../App.css' class App extends Component { render() { return ( <div className={styles.person}> <p className='fz'>person:Hello world</p> </div> ) } } }
5.Styled Components
// 依赖 npm install --save styled-components // 创建一个 Title 组件,它将渲染一个附加了样式的 <h1> 标签 const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; `; // 创建一个 Wrapper 组件,它将渲染一个附加了样式的 <section> 标签 const Wrapper = styled.section` padding: 4em; background: papayawhip; `; // 就像使用常规 React 组件一样使用 Title 和 Wrapper render( <Wrapper> <Title> Hello World! </Title> </Wrapper> }
相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36