【问题标题】:JavaScript input query string does not accept space tab but letterJavaScript 输入查询字符串不接受空格制表符而是字母
【发布时间】:2021-10-30 19:59:31
【问题描述】:

我正在为我的应用程序使用 React-native 打字稿。我有一个 TextInput,用户可以在其中传递一些值(字母/字母),该值将其传递给 Api 的查询字符串,并给出搜索结果。我制作了一个不接受任何空间的辅助函数。它只接受字母/字母。

我想制作一个带空格的辅助函数,但它只会在有字母/字母时触发。真的很难解释。但我发现Linkedin 有这种搜索过滤器,我想在我的应用程序中实现这种逻辑。但我不知道该怎么做。

这是我的代码

import debounce from 'lodash/debounce';
import React, { useState, useRef } from 'react';

const SearchScreen = () => {
  const [searchText, setSearchText] = useState('');
  const [searchedText, setSearchedText] = useState('');
  const delayedSearch = useRef(
    debounce((text: string) => {
      _search(text);
    }, 400),
  ).current;

  const _clearSearch = () => {
    if (searchText.length === 0) {
      Keyboard.dismiss();
    }
    setSearchText('');
    setSearchedText('');
  };

  const _search = (text: string) => {
    setSearchedText(text);
  };

  const removeExtraSpace = (s: string) => s.trim().split(/ +/).join(' '); // this is my helper function which does not accept white space

  const _onSearchChange = (text: string) => {
    setSearchText(removeExtraSpace(text)); // in here I am using the helper function
    delayedSearch(removeExtraSpace(text)); // in here I am using the helper function
  };

  return (
    <Container>
      <SearchBar
        text={searchText}
        onClearText={_clearSearch}
        onChangeText={_onSearchChange}
      />

      <ProductSearchResult
        queryString={searchedText} // in here I a passing Search
      />
    </Container>
  );
};

export default SearchScreen;

【问题讨论】:

  • 你没有得到的实际效果是什么?

标签: javascript react-native function validation textinput


【解决方案1】:

我犯了一个错误。我的功能工作正常。但是我错误地将函数传递给本地状态。

应该是这样的:

  const _onSearchChange = (text: string) => {
    setSearchText(text);
    delayedSearch(removeExtraSpace(text));
  };

【讨论】:

    猜你喜欢
    • 2016-07-13
    • 2012-08-18
    • 2016-08-20
    • 2014-08-03
    • 2018-10-15
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多