2

当用户在输入字段上按下回车键时,我正在尝试重定向到新路线。我有一个标题和搜索组件,我想在每个页面上呈现。我发现了使用 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;
4

3 回答 3

5

在您的 handleSubmit 函数中尝试:

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

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

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

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

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

...

<Route ... component={HomePage} />
于 2017-06-14T03:20:12.447 回答
2

由于新版本,我遇到的所有其他解决方案都已过时。

请参阅React Router V4 / 重定向

我终于通过执行以下操作解决了这个问题;

import { Redirect } from 'react-router-dom'

然后在我的状态下,我宣布“提交”为假。

postForm(e){
    e.preventDefault();
    this.setState({
      submitted : true
    })
  }

当您在渲染方法中返回时,它将检查您的状态并

render(){
    if (this.state.submitted) {
      return (
        <Redirect to="/done"/>
      )
    }
    return ( 
         something else... 
       )

我不知道这是否是好的解决方案之一,但不幸的是我无法让它以任何其他方式工作。

于 2017-06-16T12:22:33.203 回答
0

您可以在此处查看以获取有关您的案例的更多信息https://gist.github.com/verticalgrain/195468e69f2ac88f3d9573d285b09764

于 2017-06-24T15:02:45.367 回答