一、行内样式的写法
Inline Styling:
注意 是两个大括号,里边的属性要用驼峰式的写法(JS对象)
class MyHeader extends React.Component {
render() {
return (
<div>
<h1 style={{color: "red", backgroundColor: "lightblue" }}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
二、JS Object 写法
跟方法一其实是一样的
class MyHeader extends React.Component {
render() {
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
return (
<div>
<h1 style={mystyle}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
三、使用 css 文件
新建一个 app.css 文件
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Arial;
text-align: center;
}w
将 App.css 文件导入 jsx 文件
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
class MyHeader extends React.Component {
render() {
return (
<div>
<h1>Hello Style!</h1>
<p>Add a little style!.</p>
</div>
);
}
}
ReactDOM.render(<MyHeader />, document.getElementById('root'));
四、CSS Modules
新建一个文件 mystyle.module.css, 写入下面代码:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Arial;
text-align: center;
}
将上述样式文件引入组件中
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './mystyle.module.css';
class Car extends React.Component {
render() {
return <h1 className={styles.bigblue}>Hello Car!</h1>;
}
}
export default Car;
将引入 组件引入 主文件
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './App.js';
ReactDOM.render(<Car />, document.getElementById('root'));
当 style 是多个对象, 需要合并时
<div display={item.isShow} style={{...styles.hint, ...{display:"inline-block",}}}>!</div>