【发布时间】:2021-03-03 22:22:31
【问题描述】:
我有一个搜索栏,我希望用户能够在单击搜索按钮或按下回车键时调用 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;
【问题讨论】:
-
这应该抛出一个 SyntaxError。
if (e.keyCode === 13 || e == ??)。你不能像这样使用?。 -
@HåkenLid 我不能肯定地说,但我认为他只是想显示
??来问嘿,我应该在这里放什么?... -
事情是
??实际上是新的Nullish coalescing operator。它的两边都必须有一个操作数。
标签: javascript reactjs