React中使用路由進行父子組件的通信


最近我在學習 React.js 框架,在此記錄一下我使用 react-router-dom 來實現單頁應用(SPA)的路由跳轉時,怎么處理父子組件間的通信。本文使用的是 HashRouter

父組件中的路由配置

/** 
 * 我使用了 react-router-dom 里面的 Switch 進行頁面內的路由更新
 * NavPage 是父組件
 * Content 是子組件
 */

class NavPage extends React.Component {
	render () {
		return (
			<div className='body'>
				<Switch>
	  				<Route path='/navpage/content' component={Content} />
				</Switch>
			</div>
		)
	}
}


/**
 * 在父組件中定義一個方法,實現父組件跳轉到子組件並傳參數過去
 * 注意: 第一次用 push 方法,后面用 replace 方法
 * func 里面放置的是讓子組件調用的時候可以回調告訴父組件的方法
 */

navigateToSon () {
	this.props.history.replace({pathname: '/navpage/content', data: {這里以對象的方式放置要傳遞的參數}, func: this.sonCallMe})
}

sonCallMe (args) {
	console.log("My Son Call Me Now: ", args)	// 這里接收子組件傳遞過來的args,輸出:"My Son Call Me Now: 我是你兒子"
}

子組件中的配置

class Content extends React.Components {

  // 獲取父組件 NavPage 初始化傳過來的數據
  componentWillMount () {
    console.log(this.props.history.location.data)
  }
  componentWillReceiveProps () {
    console.log(this.props.history.location.data)
  }

  // 觸發父組件傳遞過來的函數去與父組件通信
  callFather () {
      this.props.history.location.func("我是你兒子")
  } 

  render () {
		return (
			<div className='body'>
				<div onClick={this.callFather.bind(this)}></div>
			</div>
		)
	}

}

我是剛踏進 React.js 大門的小白,一路上踩了很多坑。希望可以幫助到跟我一樣的小白們,有 React 方面的問題可以留言或者私信我們一起交流~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM