在根据需求实现业务的时候,我们经常会遇到组件间互相跳转和通信的问题,在具体实现业务逻辑的时候,我们会遇到各种组件间通信的情况,通过属性传递和props来解决组件间通信是比较常用的方法。
-
父子
-
父子向子组件通信 (属性传值)
Parent.jsx
import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { render() { return ( <div> <Child name="testName" /> </div> ); } } export default Parent;
Child.jsx
import React, { Component } from 'react'; class Child extends Component { constructor(props){ super(props); } render() { return ( <div> <p>{this.props.name}</p> </div> ); } } export default Child;
-
子组件向父组件通信 (回调父组件函数)
Parent.jsx
import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { constructor(props){ super(props); this.state = { name:'' } } handleChange(name){ this.setState({name}); } render() { return ( <div> <Child handleChange = {()=>this.handleChange}>{this.state.name}</Child> </div> ); } } export default Parent;
Child.jsx
import React, { Component } from 'react'; class Child extends Component { constructor(props){ super(props); this.state = { name:'' } } nameChange(e){ let name = e.target.value; this.setState({name}); } render() { return ( <div> <input onChange={()=>{this.nameChange}}/> <button onclick={()=>{this.props.handleChange(this.state.name)}}>改变</button> </div> ); } } export default Child;
-
-
祖孙
-
子组件向父组件的父组件通信 (回调父组件的父组件函数)
类似于子组件向父组件通信,唯一的区别就是函数需要多传递一层
子
—回调方法----->父
-----回调方法------>父的父
-
当前组件向子组件的子组件通信(通过属性层层传递值)
类似于父组件向子组件通信,唯一的区别就是属性值需要多传递一层
父的父
—属性值----->父
-----属性值------>子
-
-
兄弟
-
兄弟组件间通信
基本思路:一个子组件将数据通过回调函数的形式传递给父组件(共同),然后通过父组件(共同)传递给另外一个子组件
-