在打字稿的自定义搜索栏组件中使用 handleTextChange,google 自动完成

Using handleTextChange in a custom search bar component in typescript, google autocomplete

我希望搜索栏像普通搜索栏一样,在您键入时检索信息。

目前,当我在搜索栏中输入内容时,它会在我输入后立即删除我输入的任何内容。我知道 handleTextChange 属性有问题。

当我尝试在 SearchBarCustom 中传递 handleTextChange 属性时,它是 undefined

我希望这样,每当我输入内容时,相应的位置就会出现在搜索字段中。

任何帮助将不胜感激:)

const SearchBarCustom = (props) => {
  const [value, setValue] = useState('');
  return <SearchBar value={value} onChangeText={setValue} {...props} />;
};

export default class SearchScreen extends React.Component {
  render() {
    return (
      <ScrollView
        style={styles.container}
        contentInsetAdjustmentBehavior="automatic"
        stickyHeaderIndices={[0]}
      >
        <View>
          <GoogleAutoComplete
            apiKey={apiKey}
            debounce={500}
            minLength={1}
            queryTypes={'(cities)'}
          >
            {({ handleTextChange, locationResults }) => (
              <React.Fragment>
                <View style={styles.inputWrapper}>
                  <SearchBarCustom
                    onChangeText={handleTextChange} // POTENTIAL ERROR HERE
                    placeholder="Search"
                    containerStyle={{ backgroundColor: '#f3f2f8' }}
                    inputContainerStyle={{
                      backgroundColor: '#e3e3e9',
                      height: 30,
                    }}
                    placeholderTextColor="#96969b"
                    platform="ios"
                  />
                </View>
                <ScrollView>
                  {locationResults.map((el) => (
                    <LocationItem {...el} key={el.id} />
                  ))}
                </ScrollView>
              </React.Fragment>
            )}
          </GoogleAutoComplete>
        </View>
      </ScrollView>
    );
  }
}

由于 onChangeTextSearchBar 组件上的预期 prop,我认为您应该考虑通过不同的名称将 handleTextChange 传递到您的 SearchBarCustom 中,并且在 SearchBar 完成它的工作后调用它。

handleTextChange 作为 handleTextChange 而不是 onChangeText

传递到 SearchBarCustom
<SearchBarCustom
  handleTextChange={handleTextChange}
  ...
/>;

SearchBarCustom 组件上,而不是像在 onChangeText 上那样传递状态 setter 方法(setValue),为它定义一个函数并调用你的 setter 方法以及您通过的 handleTextChange

const SearchBarCustom = (props) => {
  const [value, setValue] = useState('');
  
  const onTextChangeHandler = (inputValue) => {
      setValue(inputValue);
      props.handleTextChange(inputValue)
  }

  return <SearchBar value={value} onChangeText={onTextChangeHandler} {...props} />;
};