react开发教程(八)React组件通信

前端之家收集整理的这篇文章主要介绍了react开发教程(八)React组件通信前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

父子组件通讯

通讯手段
这是最常见的通信方式,父组件只需要将子组件需要的props传给子组件,子组件直接通过this.props来使用。
通讯内容
更多要提的是如何合理的设置子组件的props,要想将子组件设计成一个复用性强的通用组件,需要将能够复用的部分抽象出来,抽象出来的props有两种形成,一种是简单的变量,另一种是抽象出来处理某种逻辑函数

以Header 组件为例

  1. //HeaderBar.jsx 子组件
  2.  
  3. import React,{ Component } from 'react';
  4.  
  5. class Header extends Component {
  6. constructor() {
  7. super();
  8. this.handleClick = (e) => {
  9. console.log(this)
  10. }
  11. }
  12.  
  13. renderLeftComponent() {
  14.  
  15. let leftDOM = {};
  16. if (this.props.renderLeftComponent) {
  17. return this.props.renderLeftComponent();
  18. }
  19.  
  20. if (this.props.showBack) {
  21. let backFunc = this.props.onBack || this.goBack;
  22. leftDOM = (<a onClick={backFunc.bind(this)}><i className="icon left-icon icon-left-arrow"></i></a>);
  23. }
  24. return leftDOM;
  25. }
  26.  
  27. renderRightComponent() {
  28. if (this.props.renderRightComponent) {
  29. return this.props.renderRightComponent();
  30. }
  31. }
  32.  
  33. goBack() {
  34. alert("返回上一页")
  35. }
  36.  
  37. render() {
  38. return (
  39. <header className="header-bar">
  40. {this.renderLeftComponent()}
  41. <span>{this.props.title || '滴滴'}</span>
  42. {this.renderRightComponent()}
  43. </header>
  44. );
  45. }
  46. }
  47.  
  48. export default Header;
  49.  
  50. //父亲组件部分代码App.jsx
  51. import HeaderBar from "./components/Header";
  52.  
  53. let leftIcon = function () {
  54. return (
  55. <a><i className="icon left-icon icon-left-haha"></i>左边按钮</a>
  56. )
  57. }
  58. class App extends Component {
  59.  
  60. render() {
  61. return (
  62. <div className="App">
  63. <HeaderBar title="滴滴打车" renderLeftComponent={leftIcon} />
  64. </div>
  65. );
  66. }
  67. }

子父组件通讯

父-子组件通信的手段是通过子组件的props是子组件用父组件的东西,子-父组件通信,是父组件用子组件的东西,暂时了解的两种方法

利用回调函数

父组件通过props传递一个方法给子组件,子组件通过props方法将子组件数据传递给父组件

利用ref

父组件通过refs调用子组件的属性

跨级组件通信

在React中当一个属性反复使用并且存在与好几个子组件中的时候,这个时候我们如果通过props一级一级传递的话可以实现多层级访问,但是这样出现一个问题就是会使代码非常混乱,在React中国年,我们还可以使用 context 来实现跨级父子组件间的通信;
在react中context称为虫洞

  1. // Component 父级
  2. class parentComponent extends React.Component {
  3. // add the following property
  4. static childContextTypes = {
  5. color: React.PropTypes.string
  6. }
  7. // 添加下面方法
  8. getChildContext() {
  9. return {
  10. color: "#f00"
  11. }
  12. }
  13. render() {
  14. <div>
  15. <Child1 />
  16. </div>
  17. }
  18. }
  19.  
  20.  
  21. // Component Child1
  22. class Child1 extends React.Component {
  23. // 添加下面属性
  24. static contextTypes = {
  25. color: React.PropTypes.string
  26. }
  27. render() {
  28. <div>{this.context.color}</div>
  29. }
  30. }

同级组件通信

同级组件之间的通信还是需要通过父组件作为中介,利用多次父-子组件通信,项目中将需要传递的数据放在了父组件的state中,变动时可以自动的同步传递。

猜你在找的React相关文章