JSX 嵌入表达式
1 | function formatName(user) { |
特定属性
const element =
const element =
防止注入攻击
React DOM 渲染时,默认会进行转义
Babel 会将 JSX 转译成 React.createElement() 函数调用
1 | const element = ( |
React 元素
1 | const element = { |
React 元素:不可变对象
组件、Props
函数组件
1 | function Welcome(props) { |
class 组件
1 | class Welcome extends React.Component { |
组件名必须大写字母开头,React 默认小写字母开头的组件为原生 DOM 标签
组件组合
1 | function Welcome(props){ |
组件拆分
Comment 组件
1 | function Comment(props) { |
组件化模块
- Avatar 组件
1 | function Avatar(props){ |
- UserInfo 组件
1 | function UserInfo(props) { |
优化后 Comment 组件
1 | function Comment(props) { |
注意:所有的 React 组件,必须保护 props 不被更改
State
State 类似于 Props,但是 State 是私有的,完全受控于当前组件
1 | class Clock extends React.Component { |
Class 组件应该始终使用 props 参数来调用父类的构造函数。
注意:
构造函数是唯一可以给 this.state 赋值的地方
state 更新可能是异步的,解决方法 this.setState((state, props) => { … })
事件处理
1 |
|
事件命名:小驼峰
JSX 中,表达式的方式插入函数
作为事件处理函数
e.preventDefault()
实现阻止默认行为
事件处理函数传参
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row
<button onClick={this.deleteRow.bind(this, id)}>Delete Row
箭头函数显示传入 e,bind方式隐式传入 e
条件渲染
&& 、 三目运算符
组件的 render 方法中返回 null 并不会影响组件的生命周期
列表、key
元素的 key 只有放在就近的数组上下文中
map() 方法中的元素需要设置 key 属性
key 只在兄弟节点间必须唯一
1 | function NumberList(props) { |
表单
受控组件
React 的 state 成为“唯一数据源”,渲染表单的 React 组件还控制着用户输入过程中表单发生的操作,被控制取值的表单输入元素即为’受控组件’
状态提升
React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state
props 只读,要修改属性值,通过”受控组件”进行修改
1 | class TemperatureInput extends React.Component { |
1 | class Calculator extends React.Component { |
组合、继承
1 | function FancyBorder(props) { |
1 | function WelcomeDialog() { |
FancyBorder JSX 标签中 所有内容
作为 children
prop 传递给 FancyBorder 组件
插槽
1 | function SplitPane(props) { |
React 中,可以将任何东西作为 props 进行传递,默认内容 children