【问题标题】:passing handleTextChange into react native elements custom searchbar component将 handleTextChange 传递给反应原生元素自定义搜索栏组件
【发布时间】:2021-04-16 21:42:24
【问题描述】:

我在下面有这段代码,我想在 SearchBarCustom 组件中传递 onchange={handleTextChange}。但是,如果我删除 onChangeText={setValue} 并在 SearchBarCustom 组件中添加 onchange={handleTextChange},我将无法在搜索栏中输入任何内容。如何传入handleTextChange?

const SearchScreen = ({}: StackNavigationProps<Routes, "SearchScreen">) => {  


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


  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} // ???
                  containerStyle={{ backgroundColor: '#f3f2f8'}}
                  inputContainerStyle={{ backgroundColor: '#e3e3e9', height: 30}}
                  placeholderTextColor = '#96969b'

                  placeholder="Search"
                  platform="ios"
                />
                </View>
              <ScrollView>
                {locationResults.map(el => (
                  <LocationItem
                  { ...el}
                  key={el.id}
                  />
                ))}
              </ScrollView>
            </React.Fragment>
          )}

        </GoogleAutoComplete>
        
        </View>
        
      </ScrollView>
    );
};

【问题讨论】:

    标签: javascript typescript react-native expo


    【解决方案1】:

    这符合 React 中所谓的受控组件。在React documentation for controlled component 中,他们解释了本地状态如何与您在框中输入的内容耦合。

    一旦以这种方式管理盒子的内容,您就会期望以不同的方式“观看”它。特别是您可能会编写类似这样的 useEffect 代码...

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

    请参阅https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect 以了解 useEffect 保护的函数如何仅在其依赖数组中的项目更改时运行(在这种情况下,数组只是 [value],因此只有在 value 时才会重新运行效果函数变化。

    【讨论】:

    • 我阅读了文档并像你说的那样使用了useEffect,但是在useEffect中未定义handleTextChange。我该如何解决这个问题?
    猜你喜欢
    • 2017-03-17
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多