重定向不适用于锚标记中的 onClick 方法
Redirect is not working with onClick method in anchor tag
我想使用 div 作为我的按钮,这里是它的代码:
<a onClick={handleLogin()}>
<div className="blu-button">
<p id="button-text-blu">LOGIN AS ADMIN <span role="img" aria-label="emoji"> </span></p>
<div className="blu-button-wrapper"></div>
</div>
</a>
这是我的 handleLogin
函数:
const handleLogin = () => {
return <Redirect to="/amnet/auth"/>
}
浏览器没有抛出任何错误。只是重定向不起作用。我已经尝试过控制台记录这件事并且它有效。
P.S。该应用程序正在 React 中开发。
试试这个。
如果你有功能组件,请使用 useHistory
钩子
import { useHistory } from "react-router-dom";
let history = useHistory();
const handleLogin = () => {
history.push("/amnet/auth")
}
如果基于 class 的组件:
const handleLogin = () => {
this.props.history.push("/amnet/auth")
}
我建议使用 props.history.push 而不是重定向组件。
如果您绝对必须使用重定向组件(例如,如果您使用的是 < 16.3 的 React),则需要在按钮所在组件的渲染函数中有条件地渲染该组件
我想使用 div 作为我的按钮,这里是它的代码:
<a onClick={handleLogin()}>
<div className="blu-button">
<p id="button-text-blu">LOGIN AS ADMIN <span role="img" aria-label="emoji"> </span></p>
<div className="blu-button-wrapper"></div>
</div>
</a>
这是我的 handleLogin
函数:
const handleLogin = () => {
return <Redirect to="/amnet/auth"/>
}
浏览器没有抛出任何错误。只是重定向不起作用。我已经尝试过控制台记录这件事并且它有效。
P.S。该应用程序正在 React 中开发。
试试这个。
如果你有功能组件,请使用 useHistory
钩子
import { useHistory } from "react-router-dom";
let history = useHistory();
const handleLogin = () => {
history.push("/amnet/auth")
}
如果基于 class 的组件:
const handleLogin = () => {
this.props.history.push("/amnet/auth")
}
我建议使用 props.history.push 而不是重定向组件。
如果您绝对必须使用重定向组件(例如,如果您使用的是 < 16.3 的 React),则需要在按钮所在组件的渲染函数中有条件地渲染该组件