React双向数据绑定
input组件双向数据绑定,需要父组件暴露一个数据更新方法传递给子组件,input使用onChange触发,然后获取对应改变的值,重新setstate,用defaultValue 替换value作为默认值
复制代码
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122//persion.js import React from 'react'; const person = ( props ) => { return ( <div> <p onClick={props.myclick}>大家好,我系{props.name},我有{props.count}作品</p> <p>{props.children}</p> <input type="text" onChange={props.changed} defaultValue={props.name}></input> </div> ) } export default person; //app.js import React from 'react'; import './App.css'; import Persion from './Persion/Persion'; class App extends React.Component { /** * state: 用于改变组件内状态的值(动态) * props: 用于组件通信传值 */ state = { persions: [ { name: '渣渣辉', count: '30' }, { name: 'aaa', count: '20' }, { name: 'bbb', count: '10' }, { name: 'ccc', count: '5' } ], otherState: 'anything' } // 函数直接定义在于render同级别,因为class类下,用this.函数名来访问 switchNameHandLer = ( newName ) => { console.log("hello") // es6中this执行为当前类 //this.state.persions[0].name = '渣渣渣渣辉' //不要直接去更改state Use setState() this.setState({ persions: [ { name: newName, count: '3000' }, { name: 'aaa', count: '20' }, { name: 'bbb', count: '10' }, { name: 'ccc', count: '5' } ] }) } nameChangedHandLer = (event) => { console.log(event.target) this.setState({ persions: [ { name: event.target.value, count: '3000' }, { name: 'aaa', count: '20' }, { name: 'bbb', count: '10' }, { name: 'ccc', count: '5' } ] }) } render () { return ( <div className="App"> hello world {/* 函数不能加括号,加括号就直接执行了,使用箭头函数可以实现参数的传递 */} {/* <button onClick={() => this.switchNameHandLer('古天乐')}>更改状态值</button> */} {/* 第二种方式 bind 传递 (建议) */} <button onClick={this.switchNameHandLer.bind(this, '古天乐')}>更改状态值</button> <Persion name={this.state.persions[0].name} count={this.state.persions[0].count} changed={this.nameChangedHandLer} /> <Persion name={this.state.persions[1].name} myclick={this.switchNameHandLer.bind(this, '渣渣辉2')} count={this.state.persions[1].count}/> <Persion name={this.state.persions[2].name} count={this.state.persions[2].count}/> <Persion name={this.state.persions[3].name} count={this.state.persions[3].count}> <a href='http://www.baidu.com'>非常感谢大家的支持</a> </Persion> </div> ); } } export default App;
触发,然后获取对应改变的值,重新setstate
最后
以上就是深情饼干最近收集整理的关于初学react(五):双向数据绑定的全部内容,更多相关初学react(五)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复