组件
这里不会将React文档中的全部内容详细的展示出来,仅会记录一些我认为很有必要记录的概念
1 分类
有函数式组件与类组件
函数式组件
f(data) = UI 函数式组件传入的props是只读的,这是为了保证函数的纯净:
- 没有可观测的副作用:不会修改组件外部的数据导致UI发生变化
- 确定性:同一个输入,必定有同一个输出。Same inputs, same output.
- 不依赖外部环境状态的:不会因为时间、地点变化 Recap
- To pass props, add them to the JSX, just like you would with HTML attributes.
- To read props, use the
function Avatar({ person, size })destructuring syntax. - You can specify a default value like
size = 100, which is used for missing andundefinedprops. - You can forward all props with
<Avatar {...props} />JSX spread syntax, but don’t overuse it! - Nested JSX like
<Card><Avatar /></Card>will appear asCardcomponent’schildrenprop. - Props are read-only snapshots in time: every render receives a new version of props.
- You can’t change props. When you need interactivity, you’ll need to set state.
类组件
部分老的项目还在使用,可以学一下,有助于理解React
2 特性
独立性,可复用与单独思考(可能就是独立性)
3 定义
一个React组件是一个可以用标记添加的JS函数 >A React component is a JavaScript function that you can sprinkle with markup.
注意
🔴React components are regular JavaScript functions, but their names must start with a capital letter or they won’t work! 必须大写函数名!
🔴Without parentheses, any code on the lines after return will be ignored! 在没有括号的情况下,就会导致return之后的内容被忽略!
return (
<div>
<img
src="https://i.imgur.com/MK3eW3As.jpg"
alt="Katherine Johnson"
/>
</div>
);🔴Never define a component inside another component! 永远不要在组件内定义组件!
4 导入
提示
🔴你可能会看到省略 .js 扩展名的写法,例如:
import Gallery from './Gallery';在 React 中,'./Gallery.js' 和 './Gallery' 都能正常工作,但前者更贴近原生 ES 模块的标准写法。
🔴How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track:
| Syntax | Export statement | Import statement |
|---|---|---|
| Default | export default function Button() {} | import Button from './Button.js'; |
| Named | export function Button() {} | import { Button } from './Button.js'; |
When you write a default import, you can put any name you want after import. For example, you could write import Banana from './Button.js' instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That’s why they are called named imports!
People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values. Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like export default () => {}, are discouraged because they make debugging harder.