首页 > 解决方案 > React:如何链接到不同的组件(在同一页面中打开)

问题描述

我有一个简单的应用程序,它有两个页面:一个用于登录,另一个用于注册。我希望他们有彼此的链接。我知道 React 链接有不同的理由,我会撒谎以听取有经验的同事关于如何做的看法。这是代码login-view

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import axios from 'axios';
import './login-view.scss';
import { RegistrationView } from '../registration-view/registration-view';

export function LoginView(props) {
  const [ username, setUsername ] = useState('');
  const [ password, setPassword ] = useState('');
// need to update handleSubmit to prevent refresh
  const handleSubmit = (e) => {
    e.preventDefault();
    /* Send a request to the server for authentication */
    axios.post('https://flix-app-test.herokuapp.com/login', {
        username: username,
        password: password
      })
      .then(response => {
        const data = response.data;
        props.onLoggedIn(data);
      })
      .catch(e => {
        console.log('no such user')
      });
  };

    const handleNewUser = (e) => {
      e.preventDefault();
      console.log('new_user');

      setUsername('New');
      props.onLoggedIn(username);
    };

  return (
    <div>
      <h1>myFlix Login</h1>
      <Form>
        <Form.Group controlId="formBasicUsername">
          <Form.Label>Username</Form.Label>
          <Form.Control type="text" value={username} onChange={e => setUsername(e.target.value)} placeholder="Enter username" />
        </Form.Group>
        <Form.Group controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Password" />
        </Form.Group>
        <Button onClick={handleSubmit}>Submit</Button>
      </Form>
    </div>

  );
}

LoginView.propTypes = {
  username: PropTypes.string.isRequired,
  password: PropTypes.string.isRequired,
  onClick: PropTypes.func.isRequired
};

这是代码registration-view

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { LoginView } from '../login-view/login-view';
import './registration-view.scss';

export function RegistrationView(props) {
  const [ username, setUsername ] = useState('');
  const [ password, setPassword ] = useState('');
  const [email, setEmail ] = useState('');
  const [birthday, setBirthday ] = useState('');
// need to update handleSubmit to prevent refresh
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(username, password, email, birthday);
    /* Send a request to the server for authentication */
    /* then call props.onLoggedIn(username) */
    props.onLoggedIn(username);

  };

  return (
    <div>
      <h1>Signup for myFlix</h1>
      <Form>
        <Form.Group controlId="formUsername">
          <Form.Label>Username</Form.Label>
          <Form.Control type="text" value={username} onChange={e => setUsername(e.target.value)} placeholder="Enter the username you want to use" />
        </Form.Group>
        <Form.Group controlId="formPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control type="text" value={password} onChange={e => setPassword(e.target.value)} placeholder="Enter a password" />
        </Form.Group>
        <Form.Group controlId="formEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="Enter email" />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
        </Form.Text>
          <Form.Group controlId="formBirthday">
            <Form.Label>Password</Form.Label>
            <Form.Control type="date" value={birthday} onChange={e => setBirthday(e.target.value)} placeholder="Enter your birthday date" />
          </Form.Group>
        </Form.Group>
        <Button onClick={handleSubmit}>Submit</Button>
      </Form>
    </div>
  );
}
RegistrationView.propTypes = {
  username: PropTypes.string.isRequired,
  password: PropTypes.string.isRequired,
  email: PropTypes.string.isRequired,
  birthday: PropTypes.string,
  onClick: PropTypes.func.isRequired
};

我被允许使用任何包,react-router-dom所以完全没有限制。提前致谢。

标签: reactjsreact-router

解决方案


您可以使用react-router. 首先在位于树顶部的组件(通常App)中配置路由器,将每个组件映射path到特定组件

import { BrowserRouter as Router, Route } from 'react-router-dom'
import { Login, Registration } from './components'

const App = () =>{
    return(
        <Router>
            <Route path='/login' component={Login} />
            <Route path='/registration' component={Registration} />
        </Router>
    )
}

现在要在组件内的路由之间进行更改,您有几个选项。其中之一是Link组件

import { Link } from 'react-router-dom'
const Login = () =>{
    return(
        <Link to='/registration'>
            Go to registration
        </Link>
    )
}

对于更命令式的 API,您应该知道路由器渲染的每个组件都注入了特殊的 props history:matchlocation. 要从处理程序内部更改当前路线,您可以使用history.push

const handleClick = () =>{
    props.history.push('/registration')
}

组件语法的路径应该与我用来导入组件的路径相同?

不是它没有。path您的组件的绝对路径与提供给的无关Router

import { Foo } from './foo'
/*...*/
<Route path='/bar' /> 

Login我尝试渲染它时,它说我不应该使用路由器外部的链接

我忘了提到要使用Link你必须在路由器上下文中。这意味着您调用的组件Link(在您的情况下Login)必须由路由器呈现。换句话说,它必须被路由,在你的一个Route组件中定义。


推荐阅读