react使用分支if
啃一口小胖安 2018/6/5 react
# react使用分支if
例如点击当前的按钮,让其他部分展示出来,再点击就收回去,不点击就不展示,
首先要拥有一个状态,这个状态控制是否展示,定义一个状态,

button定义了一个方法,实现这个方法

render里面

代码如下
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",
/*定义一个状态,控制是否展示,默认为不展示,只有为真的时候展示*/
showPersons:false
}
swithNameHandler(newName){
this.setState({
person:[
{name:newName,count:10},
{name:"xcb",count:151450},
{name:"swer",count:11},
]
})
}
nameChangedHandler(e){
this.setState({
person:[
{name:e.target.value,count:10},
{name:"xcb",count:151450},
{name:"swer",count:11},
]
})
}
togglePersonHandle(){
//先拿到当前的状态值,是真还是假
const doesShow = this.state.showPersons;
this.setState({
//如果拿到的是false,取非就变成了真,每次点击的话就是改变当前的状态
showPersons:!doesShow
})
}
render() {
const style={
backgroundColor:'white',
font:'inherit',
border:'1px solid blue',
padding:'8px',
cursor:'pointer' //小手状态
};
let persons = null; //默认是null
//如果状态为真的话,就给persons重新赋值
if(this.state.showPersons){
persons = (
<div>
<Person changed={this.nameChangedHandler.bind(this)}
name={this.state.person[0].name} count={this.state.person[0].count}/>
<Person myclick={this.swithNameHandler.bind(this,"阿斯蒂芬")} 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>
)
}
return(
<div className="App">
<h1>hello world</h1>
<p>hi,react app</p>
<button style={style} onClick={this.togglePersonHandle.bind(this)}>内容切换</button>
{persons}
</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
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
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