2

我已经搜索了一段时间,所以这不应该是重复的。但是,我试图在按下回车键时触发链接点击。

这就是我正在使用的:

handleKeyPress(target) {
  if(target.charCode==13){
    alert('Enter clicked!!!');    
  }
}

搜索输入:

<SearchBox
  type="text"
  value={value}
  onChange={e => this.onChange(e)}
  className="search-box"
  placeholder="Search"
  aria-label="search"
  aria-describedby="basic-addon2"
  onKeyPress={this.handleKeyPress}
/>
<div>
  <Link to={`/search?q=${value}`} className="btn submit-button"><i className="fa fa-search"></i></Link>
</div>

使用 React Instant Search 我想在单击输入时提交输入“值”。目前,我只能在物理单击时提交值:

<div>
  <Link to={`/search?q=${value}`} className="btn submit-button"><i className="fa fa-search"></i></Link>
</div>

我可以得到火的链接。但是,当我按下回车键时,如何获得与单击链接相同的功能?关于如何通过 KeyPress 链接到搜索值的任何建议?

4

2 回答 2

3

如果您已经react-router-dom可以使用以下内容:

import { withRouter } from 'react-router-dom'
class *ClassName* extends React.Component {
  ..
  handleKeyPress(target, value) {
    const { history } = this.props;
    if(target.charCode==13){
      history.push(`/search?q=${value}`);
    }
  }
  ..
  render() {
    return (
      ..
      <SearchBox
        value={value}
        ..
        onKeyPress={e => this.handleKeyPress(e, value)}
      />
    )
  }
  ..
}

export default withRouter(*ClassName*);

这里重要的是你使用withRouter(..)导出history从你的道具中获取。

于 2019-02-07T19:58:57.870 回答
2

根据react-statics 文档,他们建议安装 Reach Router以进行动态路由。要使用到达路由器以编程方式导航,您应该能够导入navigate.

import { navigate } from "@reach/router"

...

handleKeyPress(target) {
  // I'm guessing you have value stored in state
  const { value } = this.state;
  if(target.charCode==13){
    navigate(`/search?q=${value}`);
  }
}

选项 2

老实说,当您可能只使用 javascript来完成时,这似乎需要做很多工作。

handleKeyPress(target) {
  // I'm guessing you have value stored in state
  const { value } = this.state;
  if(target.charCode==13){
    const { href } = window.location;
    window.location.href = `${href}/search?q=${value}`;
  }
}
于 2019-02-07T19:05:24.477 回答