react開發(fā)教程之React 組件之間的通信方式
這兩天學習了React感覺組件通信這個地方知識點挺多的,而且很重要,所以,今天添加一點小筆記。
父子組件通訊
通訊手段
這是最常見的通信方式,父組件只需要將子組件需要的props傳給子組件,子組件直接通過this.props來使用。
通訊內(nèi)容
更多要提的是如何合理的設(shè)置子組件的props,要想將子組件設(shè)計成一個復(fù)用性強的通用組件,需要將能夠復(fù)用的部分抽象出來,抽象出來的props有兩種形成,一種是簡單的變量,另一種是抽象出來處理某種邏輯函數(shù)。
以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是子組件用父組件的東西,子-父組件通信,是父組件用子組件的東西,暫時了解的兩種方法
利用回調(diào)函數(shù)
父組件通過props傳遞一個方法給子組件,子組件通過props方法將子組件數(shù)據(jù)傳遞給父組件
利用ref
父組件通過refs調(diào)用子組件的屬性
跨級組件通信
在React中當一個屬性反復(fù)使用并且存在與好幾個子組件中的時候,這個時候我們?nèi)绻ㄟ^props一級一級傳遞的話可以實現(xiàn)多層級訪問,但是這樣出現(xiàn)一個問題就是會使代碼非?;靵y,在React中國年,我們還可以使用 context 來實現(xiàn)跨級父子組件間的通信;
在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> } }
同級組件通信
同級組件之間的通信還是需要通過父組件作為中介,利用多次父-子組件通信,項目中將需要傳遞的數(shù)據(jù)放在了父組件的state中,變動時可以自動的同步傳遞。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React實現(xiàn)二級聯(lián)動(左右聯(lián)動)
這篇文章主要為大家詳細介紹了React實現(xiàn)二級聯(lián)動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09詳解如何給React-Router添加路由頁面切換時的過渡動畫
這篇文章主要介紹了詳解如何給React-Router添加路由頁面切換時的過渡動畫,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04