1 | <script src="https://unpkg.com/react@16/umd/react.development.js"></script> |
- react.min.js - React 的核心库
- react-dom.min.js - 提供与 DOM 相关的功能
- babel.min.js - Babel 可以将 ES6 代码转为 ES5 代码
使用 create-react-app 快速构建 React 开发环境
1 | cnpm install -g create-react-app |
TodoList1
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60import React, {Component} from 'react';
class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
list: [],
inputValue: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
}
handleChange(e) {
this.setState({
inputValue: e.target.value
})
}
handleBtnClick() {
this.setState(
{
list: [...this.state.list, this.state.inputValue],
inputValue: ''
}
)
}
handleItemClick(index) {
let list = [...this.state.list]
list.splice(index, 1)
this.setState({
list
})
}
render() {
return (
<div>
<div>
<input value={this.state.inputValue} onChange={this.handleChange}/>
<button onClick={this.handleBtnClick} className='btn'>add</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index} onClick={this.handleItemClick.bind(this, index)}>{item}</li>
)
})
}
</ul>
</div>
)
}
}
export default TodoList
组件化todoList
1 | import React, {Component} from 'react'; |
todoItem1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import React, {Component} from 'react';
class TodoItem extends Component {
constructor(props) {
super(props)
this.handleDelete = this.handleDelete.bind(this)
}
// 子组件想要和父组件通信,要调用父组件传递过来的方法
handleDelete(index) {
this.props.delete(index)
}
// 父组件通过属性的形式向子组件传递参数
// 子组件通过props接受父组件传递过来的参数
render() {
return (
<li onClick={this.handleDelete}>{this.props.content}</li>
)
}
}
export default TodoItem