首页 > 解决方案 > 当我们在react js中移出输入字段框时如何禁用文本字段名称消失

问题描述

我使用 React js 使用 Downshift 制作了自动完成功能。但问题是当我在搜索某些内容时,当我点击外部时,它的输入字段值正在消失。这是示例代码。

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:班次 + 家也不起作用。

任何人都知道如何解决这个问题?

标签: reactjs

解决方案


当用户单击外部文本字段值时,我搜索的任何内容都消失了。

一种方法是stateReducerDownshift组件上设置:

每次 downshift 设置其内部状态时都会调用此函数(或调用您的 onStateChange 处理程序以获得控制道具)。它允许您修改将要发生的状态更改,这可以让您对组件如何与用户更新交互进行精细控制,而无需使用 Control Props。它为您提供当前状态和将要设置的状态,然后您返回要设置的状态。

state:降档的当前完整状态。

更改:这些是即将更改的属性。这还有一个 type 属性,您可以在 stateChangeTypes 部分了解更多信息。

function stateReducer(state, changes) {
  switch (changes.type) {
    case Downshift.stateChangeTypes.mouseUp:
      return {
        ...changes,
        isOpen: true,
        inputValue: state.inputValue,
      };
    default:
      return changes;
  }
}

这样,如果您在文本字段之外单击,下拉菜单将保持打开状态,并且不会重置输入值。

有关所有状态更改类型的列表,请参阅此处的文档

您也许还可以使用 上的onBlur道具使某些东西起作用input,但我没有使之起作用。


推荐阅读