简体   繁体   English

React - 输入失去对按键的关注

[英]React - input loses focus on keypress

I have run into a weird bug with my search input component where it loses focus on every keypress and can't figure out why.我的搜索输入组件遇到了一个奇怪的错误,它失去了对每个按键的关注并且无法弄清楚原因。

const App = () => {
  let [characters, setCharacters] = useState([]);
  let [filteredCharacters, setFilteredCharacters] = useState([]);
  // more state
  let [search, setSearch] = useState("");

  useEffect(() => {
    setIsLoading(true);
    axios
      .get(`https://swapi.co/api/people/?page=${pageNumber}`)
      .then(res => {
        console.log(res.data.results);
        setCharacters(res.data.results);
        setFilteredCharacters(res.data.results);
      })
      .catch(err => console.error(err))
      .then(() => {
        setIsLoading(false);
      });
  }, [pageNumber]);

  function updatePage(e) {
     // update page
  }

  function handleSearch(e) {
    setSearch(e.target.value);
    const filtered = characters.filter(character => {
      if (character.name.toLocaleLowerCase().indexOf(e.target.value) !== -1) {
        return character;
      }
    });
    setFilteredCharacters(filtered);
  }
  function SearchBar() {
    return (
      <React.Fragment>
        <StyledInput
          type="text"
          id="search"
          value={search}
          placeholder="Search by name..."
          onChange={e => handleSearch(e)}
        />
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      <GlobalStyles />
      <div className="App">
        <Heading>React Wars!</Heading>
        <SearchBar />
        <Pagination handleClick={updatePage} />
        {!isLoading && Object.entries(filteredCharacters).length ? (
          <CharacterList characters={filteredCharacters} />
        ) : (
          <LoadingBar />
        )}
      </div>
    </React.Fragment>
  );
};

I'm also getting a Line 65:50: Expected to return a value at the end of arrow function array-callback-return for the characters.filter() line so I don't know if that has to do with it.我还得到了Line 65:50: Expected to return a value at the end of arrow function array-callback-return for characters.filter()行,所以我不知道这是否与它有关。

If it helps, the deployed app with the bug can be seen here --> https://mundane-vacation.surge.sh如果有帮助,可以在此处查看已部署的带有错误的应用程序 --> https://mundane-vacation.surge.sh

You have a problem with focus because your component SearchBar is declared inside App component and it is recreated on each rendering.您的焦点有问题,因为您的组件SearchBar是在App组件中声明的,并且在每次渲染时都会重新创建它。 You need to move SearchBar out of App or just move StyledInput on the place of SearchBar .您需要将SearchBar移出App或将StyledInput移到SearchBar的位置。 If you choose the first way, I recommend you remove React.Fragment from SearchBar , because it has only one rendered child:如果您选择第一种方式,我建议您从SearchBar中删除React.Fragment ,因为它只有一个渲染的孩子:

function SearchBar(props) {
    return (
        <StyledInput
          type="text"
          id="search"
          value={props.value}
          placeholder="Search by name..."
          onChange={props.onChange}
        />
    );
  }

And in App :App中:

<SearchBar onChange={handleSearch} value={search} />

To fix your warning, you need always return a boolean value inside the filter function.要修复您的警告,您需要始终在filter function 内返回 boolean 值。 Now you return nothing (ie undefined ) in case if the character does not pass the condition.现在,如果character不通过条件,则不返回任何内容(即undefined )。 So change your filter function like this:所以改变你的filter function 像这样:

const filtered = characters.filter(character => {
    return character.name.toLocaleLowerCase().indexOf(e.target.value) !== -1
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM