【问题标题】:React redirect to another page with the Enter key without refreshing the page使用 Enter 键反应重定向到另一个页面而不刷新页面
【发布时间】:2019-02-14 08:11:01
【问题描述】:
constructor(props){
    super(props);
    this.state = { term: '' };
    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
}

onInputChange(event){
    this.setState({term: event.target.value});
    this.props.handle_search(event.target.value)
}

onFormSubmit(event){
    event.preventDefault();
    this.setState({ term: '' });
}

<form onSubmit={this.onFormSubmit} className="input-group">
    <input
        placeholder="Search games..."
        className="form-control"
        value={this.state.term}
        onChange={this.onInputChange}
   />
   <span className="input-group-btn">
       <button type="submit" className="btn btn-secondary"> 
          <NavLink to='/game_search' style={{ textDecoration: 'none' }}> Search </NavLink>
       </button>
   </span>
</form>

我正在构建一个带有搜索按钮的搜索栏。用户在搜索栏中完成输入并按下搜索按钮或“Enter 键”后,我试图重定向到另一个页面。 Redux 保留用户键入的令牌,以便在它重定向到的页面上,它可以使用存储在 Redux 中的令牌调用 API。

我现在遇到的问题是,当我在搜索栏中输入内容后按“Enter 键”时,它不会重定向到下一页。当我单击搜索按钮时,它工作得非常好,因为我在按钮标签中放置了一个 Navlink。

我试过把

this.props.history.push("/game_search")  //game search is the page it redirects to 

window.open("/game_search");
window.location.href("/game_search");

进入 onFormSubmit 方法强制它重定向到下一页,但是它刷新页面并且不保留redux中的数据。

有什么方法可以在保留数据的同时使用“Enter 键”重定向到另一个页面?提前致谢。

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

我猜你正在使用react-router-dom(因为我从那个包中看到了NavLink 组件)。

所以你实际上可以使用 this.props.history.push("/game_search") 方法,但你必须使用 HOC withRouter 在你的 SearchBar(或其他)组件中包含 React Router 的道具:

import { withRouter } from 'react-router-dom';

class SearchBar extends React.Component { .... }

export default withRouter(SearchBar);

withRouter 高阶组件会将 historymatch 路由器的 props 添加到传递的组件中。

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 2012-07-07
    • 2018-12-29
    • 1970-01-01
    • 2013-02-08
    • 2020-06-15
    • 2018-04-29
    • 2014-05-16
    相关资源
    最近更新 更多