我正在开发一个React App,试图从子组件调用父方法,下面是父组件的一些代码:
class NavigationBar extends Component {
constructor(props){
super(props);
this.state={isLoggedIn: false};
}
updateLoginState(){
alert("Login from NavigationBar");
}
GetBar() {
//const isLoggedIn = this.props.isLoggedIn;
if (false){ //isLoggedIn
return this.UserNavBar();
}
return this.StrangerNavBar();
}
StrangerNavBar(){
return (
<div>
<HashRouter>
<div>
{/* ... */}
<div className="content">
<Route exact path="/LoginCC" loginUpdate={this.updateLoginState} component={LoginCC} />
</div>
</div>
</HashRouter>
</div>
);
}
render() {
return (
this.GetBar()
);
}
}
export default NavigationBar;该组件应该使用Router根据用户是否登录来将用户重定向到不同的内容页面。如果在LoginCC.js中单击了一个按钮,就应该调用updateLoginState方法,该方法暂时只显示一条消息。子内容页面LoginCC.js如下所示:
class LoginCC extends Component {
constructor(props){
super(props);
this.state = {isLoggedIn: false};
}
render() {
return (
<div>
<HashRouter>
{/* ... */}
<Button variant="primary" size="lg" block onClick={this.props.loginUpdate}>
Log in
</Button>
{/* ... */}
</HashRouter>
</div>
);
}
}
export default LoginCC;在使用Router呈现此组件时,我将方法引用作为道具传递给LoginCC,因此如果我按下按钮,应该会弹出一条消息,但没有任何反应。
我是不是传错了道具,还是遗漏了什么?我是一个新的反应,所以任何帮助都是感激的。
发布于 2019-03-06 20:48:57
Route不会将任何自定义属性传递给组件。你应该使用其他方法来传递函数。
其中一种解决方案是:
<Route exact path="/LoginCC" render={
props => <LoginCC {...props} loginUpdate={this.updateLoginState}/>
} />请注意,updateLoginState在被调用时不会获得this。您应该对其进行bind,或者将其声明为箭头函数以获得正确的this。
https://stackoverflow.com/questions/55023291
复制相似问题