React中组件通信的几种方式

前端之家收集整理的这篇文章主要介绍了React中组件通信的几种方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

首次发表在个人博客

需要组件之进行通信的几种情况

  • 父组件向子组件通信
  • 子组件向父组件通信
  • 跨级组件通信
  • 没有嵌套关系组件之间的通信

1. 父组件向子组件通信

React数据流动是单向的,父组件向子组件通信也是最常见的;父组件通过props向子组件传递需要的信息
Child.jsx

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3.  
  4. export default function Child({ name }) {
  5. return <h1>Hello,{name}</h1>;
  6. }
  7.  
  8. Child.propTypes = {
  9. name: PropTypes.string.isrequired,};

Parent.jsx

  1. import React,{ Component } from 'react';
  2.  
  3. import Child from './Child';
  4.  
  5. class Parent extends Component {
  6. render() {
  7. return (
  8. <div>
  9. <Child name="Sara" />
  10. </div>
  11. );
  12. }
  13. }
  14.  
  15. export default Parent;

2. 子组件向父组件通信

回调函数

实现在子组件中点击隐藏组件按钮可以将自身隐藏的功能

List3.jsx

  1. import React,{ Component } from 'react';
  2. import PropTypes from 'prop-types';
  3.  
  4. class List3 extends Component {
  5. static propTypes = {
  6. hideConponent: PropTypes.func.isrequired,}
  7. render() {
  8. return (
  9. <div>
  10. 哈哈,我是List3
  11. <button onClick={this.props.hideConponent}>隐藏List3组件</button>
  12. </div>
  13. );
  14. }
  15. }
  16.  
  17. export default List3;

App.jsx

  1. import React,{ Component } from 'react';
  2.  
  3. import List3 from './components/List3';
  4. export default class App extends Component {
  5. constructor(...args) {
  6. super(...args);
  7. this.state = {
  8. isShowList3: false,};
  9. }
  10. showConponent = () => {
  11. this.setState({
  12. isShowList3: true,});
  13. }
  14. hideConponent = () => {
  15. this.setState({
  16. isShowList3: false,});
  17. }
  18. render() {
  19. return (
  20. <div>
  21. <button onClick={this.showConponent}>显示Lists组件</button>
  22. {
  23. this.state.isShowList3 ?
  24. <List3 hideConponent={this.hideConponent} />
  25. :
  26. null
  27. }
  28.  
  29. </div>
  30. );
  31. }
  32. }

观察一下实现方法,可以发现它与传统回调函数实现方法一样.而且setState一般与回调函数均会成对出现,因为回调函数即是转换内部状态是的函数传统;

3. 跨级组件通信

  • 层层组件传递props

例如A组件和B组件之间要进行通信,先找到A和B公共的父组件,A先向C组件通信,C组件通过props和B组件通信,此时C组件起的就是中间件的作用

  • 使用context

context是一个全局变量,像是一个大容器,在任何地方都可以访问到,我们可以把要通信的信息放在context上,然后在其他组件中可以随意取到;
但是React官方不建议使用大量context,尽管他可以减少逐层传递,但是当组件结构复杂的时候,我们并不知道context是从哪里传过来的;而且context是一个全局变量,全局变量正是导致应用走向混乱的罪魁祸首.

使用context

下面例子中的组件关系: ListItem是List的子组件,List是app的子组件

ListItem.jsx

  1. import React,{ Component } from 'react';
  2. import PropTypes from 'prop-types';
  3.  
  4. class ListItem extends Component {
  5. // 子组件声明自己要使用context
  6. static contextTypes = {
  7. color: PropTypes.string,}
  8. static propTypes = {
  9. value: PropTypes.string,}
  10. render() {
  11. const { value } = this.props;
  12. return (
  13. <li style={{ background: this.context.color }}>
  14. <span>{value}</span>
  15. </li>
  16. );
  17. }
  18. }
  19.  
  20. export default ListItem;

List.jsx

  1. import ListItem from './ListItem';
  2.  
  3. class List extends Component {
  4. // 父组件声明自己支持context
  5. static childContextTypes = {
  6. color: PropTypes.string,}
  7. static propTypes = {
  8. list: PropTypes.array,}
  9. // 提供一个函数,用来返回相应的context对象
  10. getChildContext() {
  11. return {
  12. color: 'red',};
  13. }
  14. render() {
  15. const { list } = this.props;
  16. return (
  17. <div>
  18. <ul>
  19. {
  20. list.map((entry,index) =>
  21. <ListItem key={`list-${index}`} value={entry.text} />,)
  22. }
  23. </ul>
  24. </div>
  25. );
  26. }
  27. }
  28.  
  29. export default List;

App.jsx

  1. import React,{ Component } from 'react';
  2. import List from './components/List';
  3.  
  4. const list = [
  5. {
  6. text: '题目一',},{
  7. text: '题目二',];
  8. export default class App extends Component {
  9. render() {
  10. return (
  11. <div>
  12. <List
  13. list={list}
  14. />
  15. </div>
  16. );
  17. }
  18. }

4. 没有嵌套关系的组件通信

在componentDidMount事件中,如果组件挂载完成,再订阅事件;在组件卸载的时候,在componentWillUnmount事件中取消事件的订阅;
以常用的发布/订阅模式举例,借用Node.js Events模块的浏览器版实现

使用自定义事件的方式

下面例子中的组件关系: List1和List2没有任何嵌套关系,App是他们的父组件;

实现这样一个功能: 点击List2中的一个按钮,改变List1中的信息显示
首先需要项目中安装events 包:

  1. npm install events --save

在src下新建一个util目录里面建一个events.js

  1. import { EventEmitter } from 'events';
  2.  
  3. export default new EventEmitter();

list1.jsx

  1. import React,{ Component } from 'react';
  2. import emitter from '../util/events';
  3.  
  4. class List extends Component {
  5. constructor(props) {
  6. super(props);
  7. this.state = {
  8. message: 'List1',};
  9. }
  10. componentDidMount() {
  11. // 组件装载完成以后声明一个自定义事件
  12. this.eventEmitter = emitter.addListener('changeMessage',(message) => {
  13. this.setState({
  14. message,});
  15. });
  16. }
  17. componentWillUnmount() {
  18. emitter.removeListener(this.eventEmitter);
  19. }
  20. render() {
  21. return (
  22. <div>
  23. {this.state.message}
  24. </div>
  25. );
  26. }
  27. }
  28.  
  29. export default List;

List2.jsx

  1. import React,{ Component } from 'react';
  2. import emitter from '../util/events';
  3.  
  4. class List2 extends Component {
  5. handleClick = (message) => {
  6. emitter.emit('changeMessage',message);
  7. };
  8. render() {
  9. return (
  10. <div>
  11. <button onClick={this.handleClick.bind(this,'List2')}>点击我改变List1组件中显示信息</button>
  12. </div>
  13. );
  14. }
  15. }

APP.jsx

  1. import React,{ Component } from 'react';
  2. import List1 from './components/List1';
  3. import List2 from './components/List2';
  4.  
  5.  
  6. export default class App extends Component {
  7. render() {
  8. return (
  9. <div>
  10. <List1 />
  11. <List2 />
  12. </div>
  13. );
  14. }
  15. }

自定义事件是典型的发布订阅模式,通过向事件对象上添加监听器和触发事件来实现组件之间的通信

总结

  • 父组件向子组件通信: props
  • 子组件向父组件通信: 回调函数/自定义事件
  • 跨级组件通信: 层层组件传递props/context
  • 没有嵌套关系组件之间的通信: 自定义事件

在进行组件通信的时候,主要看业务的具体需求,选择最合适的;
当业务逻辑复杂到一定程度,就可以考虑引入Mobx,Redux等状态管理工具

参考

reactjs官方文档
深入React技术栈
React中组件间通信的几种方式

猜你在找的React相关文章