啃一口小胖安
title: 双向数据绑定 date: 2018-06-26 tags:
- react categories:
- react
# 双向数据绑定
在react当中想要实现双向的数据绑定,需要借助于可以输入的内容,例如input。 onChang这个事件就是当你的input当中有内容,就会触发这个事件。 如果出现问题,一定要看有没有绑定bind,this指向。
# 父组件
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"
}
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},
]
})
}
render() {
return(
<div className="App">
<h1>hello world</h1>
<p>hi,react app</p>
<button onClick={this.swithNameHandler.bind(this,"撒旦法")}>更改状态值</button>
<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>
);
}
}
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
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
# 子组件
import React,{ Component } from "react";
class Person extends Component{
constructor() {
super();
// this.myclick = this.myclick.bind(this);
}
render() {
return(
<div>
<p onClick={this.props.myclick}>大家好呀,{this.props.name}有{this.props.count}个作品</p>
<p>{this.props.children}</p>
{/*这里只能用defaultValue不能用value*/}
<input type="text" onChange={this.props.changed} defaultValue={this.props.name}/>
</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