首页 编程语言 css

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>
}


相关推荐