這兩天學習了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.jsx import 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 Child1 class Child1 extends React.Component { // 添加下面屬性 static contextTypes = { color: React.PropTypes.string } render() { <div>{this.context.color}</div> } }
同級組件通信
同級組件之間的通信還是需要通過父組件作為中介,利用多次父-子組件通信,項目中將需要傳遞的數據放在了父組件的state中,變動時可以自動的同步傳遞。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com