单击按钮后,我正在尝试更改组件。我在组件的类中定义了一个changeComp()函数,当单击按钮时,我想将它路由到皮夹连接组件,但它似乎不起作用。请帮帮我,我在这里错过了什么,或者为什么这个练习是错误的?
changeComp(){
return (
<Router>
<Switch>
<Route exact path="/wallet-connect" component={WalletConnect} />
</Switch>
</Router>
);}
<button className="btn w-100 mt-3 mt-sm-4" onClick={(event) => this.changeComp(event)} type="submit">Sign In</button>发布于 2021-09-26 22:56:15
您不能从事件处理程序返回JSX并期望它被呈现到DOM中。
在您的示例中,您需要将“/wallet”Route呈现到您的主路由器中,并在changeComp回调中调用一个命令式导航。
主路由器:
<Switch>
...
<Route path="/wallet-connect" component={WalletConnect} />
...
</Switch>在有按钮的组件中:
changeComp(event) {
this.props.history.push("/wallet-connect");
}
<button
className="btn w-100 mt-3 mt-sm-4"
onClick={(event) => this.changeComp(event)}
type="submit"
>
Sign In
</button>如果组件没有注入线路道具,那么您需要用withRouter高级组件来装饰它。
建议:
因为按钮是一个type="submit",如果它是在表单中呈现的,那么只需从表单的onSubmit处理程序发出命令导航即可。
submitHandler = event => {
event.preventDefault();
...
this.props.history.push("/wallet-connect");
}
...
<form onSubmit={this.submitHandler}>
...
<button
className="btn w-100 mt-3 mt-sm-4"
type="submit"
>
Sign In
</button>
</form>如果按钮是而不是表单的部分,那么指定按钮类型为“按钮”,这样它就不会干扰任何表单元素。
<button
className="btn w-100 mt-3 mt-sm-4"
onClick={(event) => this.changeComp(event)}
type="button"
>
Sign In
</button>发布于 2021-09-26 22:28:19
changeComp(){
const history = useHistory();
return (
<Router>
<Switch>
<Route exact path="/wallet-connect" component={WalletConnect} />
</Switch>
</Router>
<button className="btn w-100 mt-3 mt-sm-4" onClick={(event) => history.push("/wallet-connect")} type="button">Sign In</button>
);}https://stackoverflow.com/questions/69339350
复制相似问题