JSX 嵌入表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}

const user = {
firstName: 'Harper',
lastName: 'Perez'
};

const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);

ReactDOM.render(
element,
document.getElementById('root')
);

特定属性

const element =

const element =

防止注入攻击

React DOM 渲染时,默认会进行转义

Babel 会将 JSX 转译成 React.createElement() 函数调用

1
2
3
4
5
6
7
8
9
10
11
12
13
const element = (
<h1 className="greeting">
Hello, world!
</h1>
)

等价于

const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
)

React 元素

1
2
3
4
5
6
7
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
}

React 元素:不可变对象

组件、Props

函数组件

1
2
3
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

class 组件

1
2
3
4
5
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

组件名必须大写字母开头,React 默认小写字母开头的组件为原生 DOM 标签

组件组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Welcome(props){
return <h2>Hello, { props.name } </h2>
}

function App(){
return (
<div> <Welcome name="Sara"/> <Welcome name="Cahal"/> <Welcome name="Edite"/> </div>
)
}

ReactDOM.render(
<App/>,
document.getElementById('root')
)

组件拆分

Comment 组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
)
}

组件化模块

  • Avatar 组件
1
2
3
4
5
6
7
8
function Avatar(props){
retrun (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
)
}
  • UserInfo 组件
1
2
3
4
5
6
7
8
9
10
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}

优化后 Comment 组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function Comment(props) {
return (
<div className="Comment">

<UserInfo user={ props.author }/>

<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
)
}

注意:所有的 React 组件,必须保护 props 不被更改

State

State 类似于 Props,但是 State 是私有的,完全受控于当前组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Clock extends React.Component {

constructor(props) {
super(props);
this.state = {date: new Date()};
}

// 生命周期方法 ↓↓↓↓↓↓
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
)
// 组件已经被渲染到 DOM 中后运行
}

componentWillUnmount() {
clearInterval(this.timerID)

}
// ↑↑↑↑↑↑

tick() {
this.setState({
date: new Date()
})
}

render() {
return (
<div>
<h1>Hello, world!</h1>

// <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>

</div>
)
}
}

ReactDOM.render(
<Clock />, // date={new Date()}
document.getElementById('root')
)
Class 组件应该始终使用 props 参数来调用父类的构造函数。

注意:

构造函数是唯一可以给 this.state 赋值的地方
state 更新可能是异步的,解决方法 this.setState((state, props) => { … })

事件处理

1
2
3
4
5
6
7
8
9

// 构造函数中必须绑定 this,否则回调中 this ==> undefined
this.activateLasers = this.activateLasers.bind(this)

// 类中方法 activateLasers

<button onClick={ activateLasers }>
事件触发
</button>

事件命名:小驼峰
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
2
3
4
5
6
7
8
9
10
11
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) =>
<ListItem key={number.toString()}
value={number} />
)}
</ul>
)
}

表单

受控组件

React 的 state 成为“唯一数据源”,渲染表单的 React 组件还控制着用户输入过程中表单发生的操作,被控制取值的表单输入元素即为’受控组件’

状态提升

React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state

props 只读,要修改属性值,通过”受控组件”进行修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}

render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'};
}

handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}

handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}

render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
)
}
}

组合、继承

1
2
3
4
5
6
7
function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
)
}
1
2
3
4
5
6
7
8
9
10
11
12
function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
)
}

FancyBorder JSX 标签中 所有内容 作为 children prop 传递给 FancyBorder 组件

插槽

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function SplitPane(props) {
return (
<div className="SplitPane">
<div className="SplitPane-left">
{props.left} // 插槽
</div>
<div className="SplitPane-right">
{props.right} // 插槽
</div>
</div>
);
}

function App() {
return (
<SplitPane
left={
<Contacts />
}
right={
<Chat />
} />
)
}

React 中,可以将任何东西作为 props 进行传递,默认内容 children