添加index.css文件
先不使用CSS preprocessor
在src 目录下添加一个新的index.css 文件,在index.js中导入
import './index.css'
注意当index.js变化时,react并不会自动刷新
在项目根目录新建.env文件, 写入下列代码则会自动刷新
FAST_REFRESH=false
在React中,我们必须使用className属性而不是 class 属性。
<li className='note'>{note.content}<button onClick={toggleImportance}>{label}</button></li>
Improved error message
新建Notification组件
const Notification = ({ message }) => {if (message === null) {return null}return (<div className="error">{message}</div>)}
样式
注意,如果border没给color, 则其color和字体color一样
.error {color: red;background-color: lightgrey;font-size: 20px;border-style: solid;border-radius: 5px;padding: 10px;margin-bottom: 10px;}
错误处理逻辑
.catch(error => {setErrorMessage(`Note '${note.content}' was already removed from server`)setTimeout(() => {setErrorMessage(null)}, 5000)setNotes(notes.filter(n => n.id !== id))})
Inline styles 内嵌样式
React的Inline styles看起来像这样
{color: 'green',fontStyle: 'italic',fontSize: 16}
- 连字符(kebab case)的 CSS 属性是用 camelCase 驼峰式编写
- 像素的数值可以简单写成整数,不带px
- 用逗号分隔(其实就是一个对象)
让我们定义一个Footer组件
const Footer = () => {const footerStyle = {color: 'green',fontStyle: 'italic',fontSize: 16}return (<div style={footerStyle}><br /><em>Note app, Department of Computer Science, University of Helsinki 2021</em></div>)}
内联样式有一定的限制, 例如不能使用伪类pseudo-classes
React哲学:构成应用功能实体的结构单元是 React 组件。 React 组件定义了组织内容的 HTML,确定功能的 JavaScript 函数,以及组件的样式; 所有这些都放在一个地方。 这是为了创建尽可能独立和可重用的单个组件。
