react-组件props
宁静致远 7/19/2020 react
- props 传递数据
- props 传递函数
import React from 'react';
import PropTypes from 'props-types';
class PropsComponent extends React.Component {
constructor() {
super()
this.state = {
list: [
{
name: '张三',
id: 1
},
{
name: '李四',
id: 2
},
{
name: '王五',
id: 3
}
]
}
}
handleSubmitTitle = (val) => {
console.log(val);
this.setState({
list: this.state.list.concat({
name: val,
id: `${Date.now()}`
})
})
}
render() {
return <div>
<Input submitTitle={this.handleSubmitTitle} />
<List list={this.state.list} />
</div>
}
}
class Input extends React.Component {
constructor(props) {
super(props)
this.state = {
input: ''
}
}
handleChangeInput = (e) => {
this.setState({
input: e.target.value
})
}
handleClickSubmit = () => {
const { submitTitle } = this.props
submitTitle(this.state.input)
this.setState({
input: ''
})
}
render() {
return <div>
<input value={this.state.input} onChange={this.handleChangeInput} />
<button onClick={this.handleClickSubmit}>提交</button>
</div>
}
}
class List extends React.Component {
constructor(props) {
super(props)
}
render() {
const { list } = this.props
return <ul>
{
list.map(item => <li key={item.id}>{item.name}</li>)
}
</ul>
}
}
export const PropsDemo = PropsComponent
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94