[英]How to do routing in react by clicking a button in class component?
我在反應類組件中有一個按鈕,如下所示
<Link to="display">
<button onClick={this.nextBtn} className="nextBtn">
Submit
</button>
</Link>
通過單擊按鈕,我需要使用函數nextBtn = () => {}
將其路由到另一個名為<Display />
組件。
我看到在函數組件中它可以通過useHistory
但在類組件中,我不知道該怎么做。
你也可以使用withRouter
from import { withRouter } from "react-router";
並注入您的組件。 您可以獲取history
作為道具並使用history.push()
導航路線。
例子:
import React from "react";
import { withRouter } from "react-router";
class ShowTheLocation extends React.Component {
nextBtn = () => {
const { history } = this.props;
history.push("/display");
};
render() {
return (
<Link to="display">
<button onClick={this.nextBtn} className="nextBtn">
Submit
</button>
</Link>
);
}
}
export default withRouter(ShowTheLocation);
您可以在類組件中使用它,如下所示:
class MyClass extends Component {
nextBtn = (param) => {
this.props.history.push({
pathname: `/display`,
});
}
...
}
你也可以試試這個。 它對我有用
import { browserHistory } from 'react-router';
class MyClass extends Component {
nextBtn = () => {
browserHistory.push('/display');
}
}
您可以通過 3 種方法路由到另一個頁面……在您的情況下,您使用的是鏈接……但是您傳遞的路由名稱是錯誤的。 你必須在前面用 / 傳遞路線名稱 .. 像這樣 ..
<Link to={'/display'}>
// display should be a routes name
<button className="nextBtn">
Submit
</button>
</Link>
https://reactrouter.com/web/api/Link .. 你可以在這里閱讀更多關於它的信息..
第二...
使用 react-router-dom 包定義路由,然后在按鈕的 onClick 事件上使用下面提到的方法之一。
1. this.props.history.push("componentpath")。
2. browserHistory 對象(在 react-router 包中)。
還要檢查這個問題的解決方案...... 如何在react js中從一個頁面導航到另一個頁面?
我假設您正在使用像 react-router 這樣的路由庫。
您想從 react-router 訪問歷史對象。 React 路由器提供了所謂的高階函數,它們可以訪問歷史並將其注入到您的類組件中。 然后在你的組件內部你可以通過 this.props.history 訪問它。
import { withRouter } from 'react-router-dom';
//JS-Example
class YourJSComponent extends Component {
/**
* Since the class gets exported wrapped in withrouter(YourComponent), history is now in the props.
*/
anyRedirectMethod = () => {
this.props.history.push("/yourRoute")
}
render(
return(
<Link to="display">
<button onClick={this.anyRedirectMethod} className="nextBtn">
Submit
</button>
</Link>
)
)
}
export default withRouter(YourJSComponent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.