React Router (Dom) v4 在输入时重定向到不同的路由回车键

查克雷诺兹

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

App.js(主要组件)

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(输入组件)

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 函数中尝试:

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

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

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

并对传递到路由中的组件执行此操作

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

...

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章