输入回车键后,React Router(Dom)v4重定向到不同的路线 [英] React Router (Dom) v4 redirect to different route upon input enter key press

查看:65
本文介绍了输入回车键后,React Router(Dom)v4重定向到不同的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在输入字段上按Enter键时,我正在尝试重定向到新路由。
我有一个我希望在每个页面上呈现的标题和搜索组件。
我找到了使用Redirect组件,withRouter组件,使用上下文以及可能将历史对象传递给我的搜索组件(输入字段所在的位置)的不同用例。任何帮助将不胜感激..

I am trying to redirect to new route when user presses enter on input field. I have a Title and Search component that I want rendered on every page. I have found different use cases with using Redirect component, withRouter component, using context, and possibly passing history object to my Search component which is where the input field lives. Any help would be appreciated..

App.js(主要组成部分)

App.js (main component)

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Title from './Title';
import Search from './Search';
import Home from './Home';
import Movie from './Movie';

class App extends Component {
    render() {
        return (
            <div>
                <Title />
                <Search />
                <Router>
                        <Switch>
                            <Route exact path='/' component={Home} />
                            <Route path='/movie' component={Movie} />
                        </Switch>
                </Router>
            </div>
        );
    }
}

export default App;

Search.js(输入组件)

Search.js (input component)

import React, { Component } from 'react';

import './Search.css';

class Search extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: ""
        }

        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({value: event.target.value});
    }
    handleSubmit(e) {
        if (e.key === 'Enter') {
            // TODO redirect user to '/movie'
        }
    }
    render() {
        return (
            <input type="text" id="searchTitle" placeholder="Search for a movie" onChange={this.handleChange} onKeyPress={this.handleSubmit} value={this.state.input} />
        )
    }
}

export default Search;


推荐答案

在handleSubmit函数中尝试:

inside your handleSubmit function try:

this.props.history.push('/movie'); // or whatever

编辑:
你可能还需要绑定它

edit: you'll probably need to bind this as well

onKeyPress={this.handleSubmit.bind(this)}

并对您传入路线的组件执行此操作

and do this to the component you're passing into the route

const HomePage = () => {
    return <Home props={this.props} />
}

...

<Route ... component={HomePage} />

这篇关于输入回车键后,React Router(Dom)v4重定向到不同的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆