最近我在學習
React.js
框架砂代,在此記錄一下我使用react-router-dom
來實現(xiàn)單頁應用(SPA)的路由跳轉(zhuǎn)時蹋订,怎么處理父子組件間的通信。本文使用的是HashRouter
刻伊。
父組件中的路由配置
/**
* 我使用了 react-router-dom 里面的 Switch 進行頁面內(nèi)的路由更新
* NavPage 是父組件
* Content 是子組件
*/
class NavPage extends React.Component {
render () {
return (
<div className='body'>
<Switch>
<Route path='/navpage/content' component={Content} />
</Switch>
</div>
)
}
}
/**
* 在父組件中定義一個方法露戒,實現(xiàn)父組件跳轉(zhuǎn)到子組件并傳參數(shù)過去
* 注意: 第一次用 push 方法,后面用 replace 方法
* func 里面放置的是讓子組件調(diào)用的時候可以回調(diào)告訴父組件的方法
*/
navigateToSon () {
this.props.history.replace({pathname: '/navpage/content', data: {這里以對象的方式放置要傳遞的參數(shù)}, 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 初始化傳過來的數(shù)據(jù)
componentWillMount () {
console.log(this.props.history.location.data)
}
componentWillReceiveProps () {
console.log(this.props.history.location.data)
}
// 觸發(fā)父組件傳遞過來的函數(shù)去與父組件通信
callFather () {
this.props.history.location.func("我是你兒子")
}
render () {
return (
<div className='body'>
<div onClick={this.callFather.bind(this)}></div>
</div>
)
}
}
我是剛踏進
React.js
大門的小白智什,一路上踩了很多坑。希望可以幫助到跟我一樣的小白們丁屎,有 React 方面的問題可以留言或者私信我們一起交流~