React组件中的DOM样式
一、行内、class、模块化
import React, { Component } from 'react';
import "./Movie.css"
import common from "./common.module.css"
class Movie extends Component {
constructor(){
super();
this.state ={
styleObj:{
fontSize:'50px'
}
}
}
render() {
return (
// 使用class
<div className="container">
{/* 行内样式 */}
<h1 style={{'fontSize':'20px'}}>正在热映</h1>
<h1 style={this.state.styleObj}>即将上映</h1>
{/* module css */}
<h1 className={common.error}>异常信息</h1>
</div>
);
}
}
export default Movie;
二、根据不同的条件添加不同的样式
npm install classnames --save
import React, { Component } from 'react';
import classNames from 'classnames/bind';
import styles from './styles.css'
let cx = classNames.bind(styles);
class Profile extends Component {
render() {
let names = cx({
inProcess:true,
error:this.props.error
})
return (
<div>
<h1 className={names}>learnginto</h1>
</div>
);
}
}
export default Profile;
三、css-in-js
styled-components
是针对React写的一套css-in-js框架,简单来讲就是在js中写css
yarn add styled-components -S
import React from 'react'
import styled from 'styled-components'
const Container = styled.div`
width:500px;
height:500px;
background:${(props)=>props.color};
font-size:30px;
`
export {
Container
}
import React, { Component } from 'react';
import {Container} from './Search_style'
class Search extends Component {
render() {
return (
<Container color="red">
<h1> hello world</h1>
</Container>
);
}
}
export default Search;
网友评论