我是 React 新手,在从子级设置父级状态时遇到困难。
父组件:Router.js
class Router extends Component{
constructor(props){
super(props);
this.handler = this.handler.bind(this);
this.state = {
login: true,
}
}
handler() {
console.log("hi");
this.setState({
login: true,
});
}
render(){
return(
<div>
<BrowserRouter>
<Route exact path="/" component={ Register }></Route>
...other routes
<Route path="/login" handler={this.handler} component={ Login } />
</div>
);
}
}
export default Router;
子组件Login.js
class Login extends Component {
...some code to get back end node js data
if(got node data){
this.props.handler();
this.props.history.push('/home');
}
render (){
return (
<div>
<button className="button" onClick = {this.checkUser.bind(this)}>
Login
</button>
<div>
)
}
我不断收到“this.props.handler 不是一个函数”
我的处理程序格式是否错误?我有点困惑。
谢谢
最佳答案
当您这样做时,您将 this.handler
传递给 Route
组件,而不是传递给 Login
<Route path="/login" handler={this.handler} component={ Login } />
您有两种选择将 this.handler
传递给 Login
组件。
您可以通过 render 传递 Prop
<Route path="/login" render={ () => <Login handler={this.handler} />} />
或者嵌套它
<Route path="/login">
<Login handler={this.handler} />
</Route>
关于javascript - this.props.function 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60515554/