ReactRouter中父子组件如何通信

父组件App中有个callback方法想要传递给子组件Objective,不使用ReactRouter时可以通过props传递

//App中
callback=()=>{console.log(1)};
<Objective callback={this.callback}></Objective>
//Objective中
this.props.callback();//1

但是启用ReactRouter后,怎么给Objective组件传递方法呢
直接这么写是获取不到callback方法的

//App中
callback=()=>{console.log(1)};
<Route path="/objective" component={Objective} callback={this.callback}></Route>
//Objective中
this.props.callback();//callback不存在
阅读 2.3k
2 个回答
<Route path="/objective" component={() => <Objective callback={this.callback} />} ></Route>

这是最简单直接的方式

<Route path="/objective" component={Objective} callback={this.callback}></Route>

你这样写,你觉得 callback 传到哪里去了??? callback 是谁的 prop ???


const ObjectiveComp = (<Objective callback={this.callback}></Objective>)

<Route path="/objective" component={ObjectiveComp}></Route>

这样写,那你觉得 callback 是谁的 prop 呢???

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题