简体   繁体   English

如何在React的模式/对话框中传递路由器道具进行导航

[英]How to pass router props in a Modal/Dialog in React for navigation

I am stuck on a problem. 我陷入一个问题。 I have added a login component in my React-Project. 我在我的React-Project中添加了一个登录组件。 That login module is in a modal/dialog form. 该登录模块为模式/对话框形式。 Login component button resides in Header component of the project. 登录组件按钮位于项目的页眉组件中。 As usual i am not setting a router path for this login module and so i am not able to set the props. 像往常一样,我没有为此登录模块设置路由器路径,因此无法设置道具。 I don't want to move login component in a separate as thats the requirement. 我不想将登录组件单独移动,因为这就是要求。 So how should i get history props to check the page route 那么我应该如何获得history props来检查页面路线

Part of Header component that opens up the login dialog window Header组件的一部分,用于打开登录对话框窗口

{
  this.state.sessionValid ? (
    <div className="flex">
      <Button edge="end" color="inherit" onClick={this.openLogin.bind(this)}>
        Login
      </Button>
      <Button edge="end" color="inherit" onClick={this.openSignup.bind(this)}>
        Signup
      </Button>
    </div>
  ) : (
    <div>
      <Button edge="end" color="inherit">
        Logout
      </Button>
    </div>
  );
}

Login component: 登录组件:

render() {
  return (
    <div>
      <Dialog
        open={this.props.openLogin}
        TransitionComponent={Transition}
        keepMounted
        onClose={this.props.closeLogin}
        aria-labelledby="alert-dialog-slide-title"
        aria-describedby="alert-dialog-slide-description"
      >
        <DialogContent style={{ padding: 50 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <h2>Login</h2>
            <CardMedia
              component="img"
              alt="Image for signup"
              style={{ width: "30%", borderRadius: 5 }}
              image="logo.png"
              title="Front"
            />
          </div>

          <form style={{ marginTop: 0 }} onSubmit={this.submit.bind(this)}>
            <div>
              <TextField
                fullWidth={true}
                required={true}
                label="Email"
                value={this.state.formData.email}
                onChange={this.handleChange.bind(this, "email")}
                margin="normal"
              />
            </div>

            <Button color="primary" type="submit" disabled={this.formCheck()}>
              Login
            </Button>

            <Button color="primary" onClick={this.props.openSignupInstead}>
              Signup
            </Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}

Part of Router function. 路由器功能的一部分。

return (
    <div>
      <BrowserRouter>
        <header className="mainHeader">
          <HeaderComponent />
        </header>

Dirty way 肮脏的方式

You can pass history as props of your <HeaderComponent /> 您可以将历史记录作为<HeaderComponent />道具传递

import { createBrowserHistory } from "history";
const history = createBrowserHistory();
...
export default function main() {
    ...
    return (
    <div>
      <BrowserRouter history={history>
        <header className="mainHeader">
          <HeaderComponent history={history} />
        </header>
}

I used this technic many times, works like a charm but get really messy and difficult to maintain. 我曾多次使用过这种技术,其工作原理很吸引人,但是却变得凌乱且难以维护。

React Hooks: useRouter React Hooks:useRouter

Since react 16.8 introduced hooks , you can use that to define your component, and then use the react router useRouter hook anywhere to access your router and access history. 由于react 16.8引入了hooks ,因此您可以使用它来定义您的组件,然后在任何地方使用react router useRouter钩子来访问路由器和访问历史记录。

import * as React from "react";
import { Router, Route } from "react-router-dom";

const RouterContext = React.createContext(null);

export const HookedBrowserRouter = ({ children, history }) => (
  <Router history={history}>
    <Route>
      {routeProps => (
        <RouterContext.Provider value={routeProps}>
          {children}
        </RouterContext.Provider>
      )}
    </Route>
  </Router>
);

export function useRouter() {
  return React.useContext(RouterContext);
}

Replace your <BrowserRouter> with <HookedBrowserRouter history={history}> you just defined 用您刚定义的<HookedBrowserRouter history={history}>替换您的<BrowserRouter>

Then in any component using react hooks: 然后在任何组件中使用react挂钩:

import { useRouter } from "../router";

export default function YourComponent() {
  const { history } = useRouter();
  // Do something with history
  return <div />;
}

Login component is shown by clicking on a button on header component. 通过单击标题组件上的按钮来显示登录组件。 So here i am using window's location feature to work. 所以在这里,我正在使用窗口的位置功能。 I am providing an overview of this, so that you may get a little idea. 我对此进行了概述,以便您有所了解。

export default class HeaderComponent extends Component {
   .
   .
submitLogin = () =>{
    window.location.href= '/'
 }
   .
   .

render() {
   return (
    <div>
   .
   .
<LoginComponent
    openLogin={this.state.openLogin}
    closeLogin={this.closeLogin.bind(this)}
    openSignupInstead={this.openSignupInstead.bind(this)}
    submitLogin={this.submitLogin.bind(this)} />
   .
   .
 </div>
)}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM