首页 > 解决方案 > 如果事件是 Enter Button 或鼠标单击,则执行某些操作

问题描述

我有一个搜索栏,我希望用户能够在单击搜索按钮或按回车键时调用 handleSearch 函数。搜索按钮工作正常,但我无法在按下回车键时让它工作。请帮忙 :)

import React, { useState } from 'react';
import { Form, FormControl, Button } from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { searchBlogs, setSearchQuery } from '../../actions/searchBlogsAction';

function SearchComponent() {
  const history = useHistory();
  const dispatch = useDispatch();
  const [searchInput, setSearchInput] = useState('');

  const inputHandler = (e) => {
    setSearchInput(e.target.value);
  };

  // Search blogs and redirect to the search results page
  const handleSearch = (e) => {
    if (e.keyCode === 13 || e == ??) {
      e.preventDefault();
      history.push('/search-results');
      dispatch(setSearchQuery(searchInput));
      dispatch(searchBlogs(searchInput));
      setSearchInput('');
    }
  };

  return (
    <Form inline>
      <FormControl
        type="text"
        size="sm"
        placeholder="Search"
        className="mr-sm-2"
        onChange={inputHandler}
        value={searchInput}
        onKeyPress={handleSearch}
      />
      <Button size="sm" variant="outline-secondary" onClick={handleSearch}>
        Search
      </Button>
    </Form>
  );
}

export default SearchComponent;

标签: javascriptreactjs

解决方案


尝试这个:

      <FormControl
        type="text"
        size="sm"
        placeholder="Search"
        className="mr-sm-2"
        onChange={inputHandler}
        value={searchInput}
        onKeyPress={event => event.key === "Enter" && handleSearch()}
      />

handleSearch函数应该是:

  const handleSearch = (e) => {
      e.preventDefault();
      history.push('/search-results');
      dispatch(setSearchQuery(searchInput));
      dispatch(searchBlogs(searchInput));
      setSearchInput('');
  }

推荐阅读