1.父组件向子组件传值
state:传递数据
props:接收数据
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24//父组件 class Parent extends React.Component { state = { lastName: 'Tom' } render(){ return( <div className="parent"> 父组件: <Child name={this.state.lastName}/> </div> ) } } //子组件 const Child = (props) => { return ( <div className="child"> <p>子组件:接收到父组件的数据:{props.name}</p> </div> ) } ReactDOM.render(<Parent/>,document.getElementById('root'))
2.子组件向父组件传值
复制代码
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//父组件 class Parent extends React.Component { state = { parentMsg: '' } //提供回调函数,用来接收数据 getChildMsg = (data) =>{ console.log('接收到子组件中传递过来的数据',data) this.setState({ parentMsg: data }) } render(){ return( <div className="parent"> 父组件:{this.state.parentMsg} <Child getMsg={this.getChildMsg}/> </div> ) } } //子组件 class Child extends React.Component { state = { msg:'敲代码' } handelCilck = () => { //子组件调用父组件中传递过来的数据 this.props.getMsg(this.state.msg); } render() { return ( <div className="child"> 子组件:<button onClick={this.handelCilck}>点击,给父组件传递数据</button> </div> ) } } ReactDOM.render(<Parent/>,document.getElementById('root'))
3.兄弟组件
状态提升思想
复制代码
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//父组件 class Counter extends React.Component { //提供共享状态 state = { count: 0 } //提供修改状态的方法 onIncrement = ()=>{ this.setState({count: this.state.count + 1}); } render() { return ( <div> <Child1 count={this.state.count}/> <Child2 onIncrement={this.onIncrement}/> </div> ) } } const Child1 = (props) => { return ( <h1>计数器:{props.count}</h1> ) } const Child2 = (props) => { return ( <button onClick={() => {props.onIncrement()}}>+1</button> ) } ReactDOM.render(<Counter/>,document.getElementById('root'))
最后
以上就是神勇花卷最近收集整理的关于react组件间通信的三种方式的全部内容,更多相关react组件间通信内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复