我设计了这个简单的搜索,一旦单击搜索,它就会显示动画。我的问题是我想重复使用“搜索”按钮,以便用户再次输入后再次单击它即可进行实际搜索。
再次单击该按钮将触发onBlur,它失去焦点,我的输入消失,然后再次触发搜索。我该怎么做才能使其真正执行搜索,而不是触发onBlur ...
所需的效果:单击搜索,输入出现,在输入外部单击,由于onBlur输入消失,再次单击搜索,键入内容,单击搜索不会触发onBlur,但实际上会执行搜索,例如通过调用其他函数
const {useState} = React;
const Nav = () => {
const [isSearchOn, setIsSearchOn] = useState(false);
const [searchValue, setSearchValue] = useState("");
let searchInput;
const onSearchBlur = () => {
setIsSearchOn(false);
setSearchValue("");
console.log("onBlur ", searchValue);
};
const onSearchChange = event => {
setSearchValue(event.target.value);
};
const handleSearchClick = () => {
if (!isSearchOn) {
setIsSearchOn(true);
searchInput.focus();
}
console.log("searchClick = ", isSearchOn);
};
const handleSearch = () => {
console.log("Perform the search");
};
return (
<nav>
<input
value={searchValue}
id="search"
placeholder="Search..."
className={isSearchOn ? "search-on" : ""}
ref={input => {
searchInput = input;
}}
onChange={onSearchChange}
onBlur={onSearchBlur}
/>
<button onClick={handleSearchClick}>
Search
</button>
</nav>
);
}
ReactDOM.render(
<Nav />,
document.getElementById("root")
);
body {
background-color: #444;
}
input {
border: none;
background: none;
color: white;
outline: none;
text-align: right;
padding: 10px;
transform: translateX(-50%);
opacity: 0;
transition: ease-in-out 0.2s;
}
input:focus {
transform: translateX(0);
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 0 :(得分:0)
e.preventDefault
是您可能的解决方案。我修改了您的搜索处理程序,如下所示。您本质上是想防止事件冒泡。这是您可以使用的工作版本:https://stackblitz.com/edit/react-xis1gp
const { useState } = React;
export const Nav = () => {
const [isSearchOn, setIsSearchOn] = useState(false);
const [searchValue, setSearchValue] = useState("");
let searchInput;
const onSearchBlur = (e) => {
e.preventDefault();
setIsSearchOn(false);
setSearchValue("");
console.log("onBlur ", searchValue);
};
const onSearchChange = event => {
setSearchValue(event.target.value);
};
const handleSearchClick = (e) => {
e.preventDefault();
if (!isSearchOn) {
setIsSearchOn(true);
searchInput.focus();
}
console.log("searchClick = ", isSearchOn);
};
const handleSearch = () => {
console.log("Perform the search");
};
return (
<nav>
<input
value={searchValue}
id="search"
placeholder="Search..."
className={isSearchOn ? "search-on" : ""}
ref={input => {
searchInput = input;
}}
onChange={onSearchChange}
onBlur={onSearchBlur}
/>
<button onClick={handleSearchClick}>
Search
</button>
</nav>
);
}