Voyz's Studio.

React学习笔记(三)

字数统计: 448阅读时长: 2 min
2019/04/16 Share

TodoList小项目

项目结构

react_demo_struc.png

代码

  • index.js
1
2
3
4
5
import React from 'react';
import ReactDOM from 'react-dom';
import ToDoList from './ToDoList';

ReactDOM.render(<ToDoList />, document.getElementById('root'));
  • ToDoList.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import React , { Component,Fragment } from "react";
import ToDoItem from "./Components/ToDoItem";
import './style.css'

class ToDoList extends Component {
constructor(props){
super(props);
this.state = {
inputValue:'',
list:[]
}
this.handleInputChange = this.handleInputChange.bind(this)
this.handelButtonClick = this.handelButtonClick.bind(this)
}

render() {
return (
<Fragment>
<div>
<input
className = 'input'
value = {this.state.inputValue}
onChange={this.handleInputChange}
/>
<button onClick = {this.handelButtonClick}>
提交
</button>
</div>

<div>
<ul>
{
this.state.list.map((val,idx)=>{
return (
<ToDoItem
key={idx}
val = {val}
delete_myself = {this.delelteItem.bind(this)}
/>
)
})
}
</ul>
</div>

</Fragment>

)
}

handleInputChange(e){
const value = e.target.value
this.setState(()=>{
return {
inputValue:value
}
})
}

handelButtonClick(){
this.setState((preState)=>({
list:[...this.state.list,this.state.inputValue],
inputValue:''
}))
}

delelteItem(idx){
this.setState((preState)=>{
const list = [...preState.list];
list.splice(idx,1);
return {list}
})
}
}

export default ToDoList

  • ./Components/ToDoItem.js
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
import React,  { Component } from "react";

export default class ToDoItem extends Component {
constructor(props){
super(props);
this.delete_myself = this.delete_myself.bind(this)
this.state= {
}
}

render(){
const { val } = this.props
return (
<div onClick={this.delete_myself}>
{/* dangerouslySetInnerHTML = {{__html: val}} */}
{val}
</div>
)
}

delete_myself(){
const { idx } = this.props
this.props.delete_myself(idx)
}
}
  • ../public/index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

CATALOG
  1. 1. TodoList小项目
    1. 1.1. 项目结构
    2. 1.2. 代码