国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

react開發教程之React 組件之間的通信方式

2019-11-19 15:49:24
字體:
來源:轉載
供稿:網友

這兩天學習了React感覺組件通信這個地方知識點挺多的,而且很重要,所以,今天添加一點小筆記。

父子組件通訊

通訊手段

這是最常見的通信方式,父組件只需要將子組件需要的props傳給子組件,子組件直接通過this.props來使用。

通訊內容

更多要提的是如何合理的設置子組件的props,要想將子組件設計成一個復用性強的通用組件,需要將能夠復用的部分抽象出來,抽象出來的props有兩種形成,一種是簡單的變量,另一種是抽象出來處理某種邏輯函數。

以Header 組件為例

//HeaderBar.jsx 子組件import React, { Component } from 'react';class Header extends Component {  constructor() {    super();    this.handleClick = (e) => {      console.log(this)    }  }  renderLeftComponent() {    let leftDOM = {};    if (this.props.renderLeftComponent) {      return this.props.renderLeftComponent();    }    if (this.props.showBack) {      let backFunc = this.props.onBack || this.goBack;      leftDOM = (<a onClick={backFunc.bind(this)}><i className="icon left-icon icon-left-arrow"></i></a>);    }    return leftDOM;  }    renderRightComponent() {    if (this.props.renderRightComponent) {      return this.props.renderRightComponent();    }  }  goBack() {    alert("返回上一頁")  }  render() {    return (      <header className="header-bar">        {this.renderLeftComponent()}        <span>{this.props.title || '滴滴'}</span>        {this.renderRightComponent()}      </header>    );  }}export default Header;//父親組件部分代碼App.jsximport HeaderBar from "./components/Header";let leftIcon = function () { return (  <a><i className="icon left-icon icon-left-haha"></i>左邊按鈕</a> )}class App extends Component { render() {  return (   <div className="App">    <HeaderBar title="滴滴打車" renderLeftComponent={leftIcon} />   </div>  ); }}

子父組件通訊

父-子組件通信的手段是通過子組件的props是子組件用父組件的東西,子-父組件通信,是父組件用子組件的東西,暫時了解的兩種方法

利用回調函數

父組件通過props傳遞一個方法給子組件,子組件通過props方法將子組件數據傳遞給父組件

利用ref

父組件通過refs調用子組件的屬性

跨級組件通信

在React中當一個屬性反復使用并且存在與好幾個子組件中的時候,這個時候我們如果通過props一級一級傳遞的話可以實現多層級訪問,但是這樣出現一個問題就是會使代碼非常混亂,在React中國年,我們還可以使用 context 來實現跨級父子組件間的通信;

在react中context稱為蟲洞

// Component 父級class parentComponent extends React.Component {    // add the following property  static childContextTypes = {    color: React.PropTypes.string  }    // 添加下面方法  getChildContext() {    return {      color: "#f00"    }  }    render() {    <div>      <Child1 />    </div>  }}// Component Child1class Child1 extends React.Component {  // 添加下面屬性  static contextTypes = {    color: React.PropTypes.string  }    render() {    <div>{this.context.color}</div>  }}

同級組件通信

同級組件之間的通信還是需要通過父組件作為中介,利用多次父-子組件通信,項目中將需要傳遞的數據放在了父組件的state中,變動時可以自動的同步傳遞。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 峡江县| 桑植县| 稷山县| 故城县| 镇平县| 兴国县| 赤城县| 大庆市| 当涂县| 安泽县| 咸阳市| 六盘水市| 德安县| 奎屯市| 虹口区| 崇义县| 常山县| 太康县| 巨野县| 福安市| 清流县| 石狮市| 新源县| 封丘县| 凌海市| 吴旗县| 呼和浩特市| 天峨县| 安泽县| 陈巴尔虎旗| 荆州市| 和田市| 汪清县| 古浪县| 富平县| 都昌县| 会泽县| 沙河市| 定安县| 台安县| 长葛市|