我已经使用react js的降档功能实现了自动完成功能。但问题是,当我在搜索某个东西时,当我单击外部时,它的输入字段值就消失了。以下是示例代码。
import logo from './logo.svg';
import './App.css';
import React, { useState } from "react";
import Highlighter from "react-highlight-words";
import Downshift from "downshift";
import axios from 'axios';
function App() {
const [names, setnames] = useState([{
const [searchTerm, setSearchTerm] = useState('')
const [movie, setmovie] = useState([])
fetchMovies = fetchMovies.bind(this);
inputOnChange = inputOnChange.bind(this);
function inputOnChange(event) {
if (!event.target.value) {
return;
}
fetchMovies(event.target.value);
}
function downshiftOnChange(selectedMovie) {
alert(`your favourite movie is ${selectedMovie.title}`);
}
function fetchMovies(movie) {
const moviesURL = `https://api.themoviedb.org/3/search/movie?api_key=1b5adf76a72a13bad99b8fc0c68cb085&query=${movie}`;
axios.get(moviesURL).then(response => {
setmovie(response.data.results);
// this.setState({ movies: response.data.results });
});
}
return (
<Downshift
onChange={downshiftOnChange}
itemToString={item => (item ? item.title : "")}
>
{({
selectedItem,
getInputProps,
getItemProps,
highlightedIndex,
isOpen,
inputValue,
getLabelProps
}) => (
<div>
<label
style={{ marginTop: "1rem", display: "block" }}
{...getLabelProps()}
>
Choose your favourite movie
</label>{" "}
<br />
<input
{...getInputProps({
placeholder: "Search movies",
onChange: inputOnChange
})}
/>
{isOpen ? (
<div className="downshift-dropdown">
{movie
.filter(
item =>
!inputValue ||
item.title
.toLowerCase()
.includes(inputValue.toLowerCase())
)
.slice(0, 10)
.map((item, index) => (
<div
className="dropdown-item"
{...getItemProps({ key: index, index, item })}
style={{
backgroundColor:
highlightedIndex === index ? "lightgray" : "white",
fontWeight: selectedItem === item ? "bold" : "normal"
}}
>
{item.title}
</div>
))}
</div>
) : null}
</div>
)}
</Downshift>
);
}
export default App;这是我写的示例代码。此外,当我单击shift+home时,它也不工作。
问题1:当用户单击外部文本字段值时,无论我搜索什么,它都会消失。
问题2: shift + home也不起作用。
有谁知道怎么解决这个问题吗?
发布于 2021-05-23 17:08:34
当用户单击外部文本字段值时,无论我搜索什么,它都会消失。
一种方法是在Downshift组件上设置stateReducer:
每次降档设置其内部状态(或调用控制道具的onStateChange处理程序)时,将调用此函数。它允许您修改将要发生的状态更改,这可以让您对组件如何与用户更新交互进行细粒度控制,而不必使用control Props。它为您提供当前状态和将要设置的状态,然后返回您想要设置的状态。状态:降档的完整当前状态。更改:这些是即将更改的属性。它还有一个类型属性,您可以在stateChangeTypes小节中了解更多信息。
function stateReducer(state, changes) {
switch (changes.type) {
case Downshift.stateChangeTypes.mouseUp:
return {
...changes,
isOpen: true,
inputValue: state.inputValue,
};
default:
return changes;
}
}这样,如果您在文本字段之外单击,下拉列表将保持打开状态,并且输入值不会被重置。
有关所有状态更改类型的列表,请参阅文档here
你也可以在input上使用onBlur属性来运行一些东西,但是我没有让它运行。
https://stackoverflow.com/questions/67553419
复制相似问题