state,props
啃一口小胖安 2018/6/4 react
# state
不是用来传值的而是用来改变一个值的状态。是动态的
# props
进行属性传值,组件和组件之间的通信,属性这个东西我们不会去进行改变
我们需要一个地方可以为被修改的内容,被修改的内容就不能写死在字符串里面,而是我们可以通过触发一个事件,然后能够修改某一个内容,这个时候我们就需要state,state是component提供给我们的一个状态,只能应用于class,而且这个class还是继承component的。
# 父组件app.js
import React, { Component } from 'react';
import './App.css';
import Person from './component/person';
class App extends Component {
/*
state:用于改变组件内容状态的值(动态)
props:用于组件通信进行传值。
* */
state = {
person:[
{name:"sdf",count:10},
{name:"sasdf",count:151450},
{name:"swer",count:1854651}
],
otherState:"anhthing"
}
swithNameHandle = () =>{
this.setState({
person:[
{name:"xcvb",count:10},
{name:"xcb",count:151450},
{name:"swer",count:11}
]
})
}
render() {
return (
<div className="App">
<h1>hello world</h1>
<p>hi,react app</p>
<button onClick={this.swithNameHandle}>更改状态值</button>
<Person name={this.state.person[0].name} count={this.state.person[0].count}/>
<Person name={this.state.person[1].name} count={this.state.person[1].count}/>
<Person name={this.state.person[2].name} count={this.state.person[2].count}>
真的好呀
</Person>
</div>
);
}
}
export default App;
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
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
# 子组件person.js
import React,{ Component } from "react";
class Person extends Component{
constructor() {
super();
}
render() {
return (
<div>
<p>大家好呀,{this.props.name}有{this.props.count}个作品</p>
<p>{this.props.children}</p>
</div>
);
}
}
export default Person;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20