這兩天學(xué)習(xí)了React感覺(jué)組件通信這個(gè)地方知識(shí)點(diǎn)挺多的,而且很重要,所以,今天添加一點(diǎn)小筆記。
父子組件通訊
通訊手段
這是最常見(jiàn)的通信方式,父組件只需要將子組件需要的props傳給子組件,子組件直接通過(guò)this.props來(lái)使用。
通訊內(nèi)容
更多要提的是如何合理的設(shè)置子組件的props,要想將子組件設(shè)計(jì)成一個(gè)復(fù)用性強(qiáng)的通用組件,需要將能夠復(fù)用的部分抽象出來(lái),抽象出來(lái)的props有兩種形成,一種是簡(jiǎn)單的變量,另一種是抽象出來(lái)處理某種邏輯函數(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("返回上一頁(yè)") } 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="滴滴打車(chē)" renderLeftComponent={leftIcon} /> </div> ); } }
子父組件通訊
父-子組件通信的手段是通過(guò)子組件的props是子組件用父組件的東西,子-父組件通信,是父組件用子組件的東西,暫時(shí)了解的兩種方法
利用回調(diào)函數(shù)
父組件通過(guò)props傳遞一個(gè)方法給子組件,子組件通過(guò)props方法將子組件數(shù)據(jù)傳遞給父組件
利用ref
父組件通過(guò)refs調(diào)用子組件的屬性
跨級(jí)組件通信
在React中當(dāng)一個(gè)屬性反復(fù)使用并且存在與好幾個(gè)子組件中的時(shí)候,這個(gè)時(shí)候我們?nèi)绻ㄟ^(guò)props一級(jí)一級(jí)傳遞的話(huà)可以實(shí)現(xiàn)多層級(jí)訪問(wèn),但是這樣出現(xiàn)一個(gè)問(wèn)題就是會(huì)使代碼非常混亂,在React中國(guó)年,我們還可以使用 context 來(lái)實(shí)現(xiàn)跨級(jí)父子組件間的通信;
在react中context稱(chēng)為蟲(chóng)洞
// Component 父級(jí) 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> } }
同級(jí)組件通信
同級(jí)組件之間的通信還是需要通過(guò)父組件作為中介,利用多次父-子組件通信,項(xiàng)目中將需要傳遞的數(shù)據(jù)放在了父組件的state中,變動(dòng)時(shí)可以自動(dòng)的同步傳遞。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com