【问题标题】:Search bar React Native搜索栏 React Native
【发布时间】:2017-06-29 11:46:50
【问题描述】:

我需要为我的应用创建搜索栏。我目前正在使用react-native-material-ui,this,但我有问题。

1- 它会导致真实设备上的延迟。

2- 我如何在“搜索栏”中搜索项目。我的渲染方法上有这段代码:

<View style={{marginBottom: 50}}>
    <ThemeProvider uiTheme={uiTheme}>
        <Toolbar uiTheme={uiTheme}
                 leftElement="arrow-back"
                 onLeftElementPress={() => goBack()}
                 centerElement={params.tapName}
                 searchable={{
                       autoFocus: true,
                       placeholder: 'Search',
                       onChangeText: (text) => {    
                               this.setState({currentSearch: text});
                               for (var i = 0; i < this.state.brands.length; i++) {  
if(this.state.brands[i].name.search(text) != -1)                            
     console.warn(this.state.brands[i].name);}},
                                }}
                              />
       </ThemeProvider>
    </View>

我可以找到品牌的名称,但无法过滤和呈现它们。如果您知道如何呈现这些过滤的项目,或者知道更好的搜索栏,我正在等待您的答案。

【问题讨论】:

  • 你应该不能访问onChangeText中的状态变量
  • 您可以将您的搜索代码添加到另一个函数中并调用onChangeText

标签: android reactjs react-native material-ui searchbar


【解决方案1】:

onChangeText 替换为

onChangeText={(text) => this.searchItem({text})}

并添加一个函数searchItem 并将您的搜索逻辑放入此函数中。

searchItem(text) {
        for (var i = 0; i < this.state.brands.length; i++) {  
            if(this.state.brands[i].name.search(text) != -1)                            
                console.warn(this.state.brands[i].name);
        }
}

编辑

我正在使用两个状态变量:initialDatafilteredData。在初始状态下,我已将主要源数据分配给两个变量。

filteredData 用作datasource。一旦用户搜索比较textinitialData。如果您有匹配的结果,则创建一个数组并使用该结果更新filteredData

如果要清除过滤结果,请将主源initialData 分配给filteredData

希望对你有帮助。

【讨论】:

  • fly...我已经创建了自定义搜索栏。
  • 它不过滤品牌。我可以看到它们被过滤的警告,但在渲染部分,它们没有被过滤。
  • 您需要使用过滤结果更新您的初始列表状态。
  • 我怎样才能做到这一点?我在加载页面时生成列表,componentDidMount 方法。之后,每当我尝试使用名称、列表项时,我都会将它们称为 {this.state.name}。我该如何更新?
  • 我有两个状态变量,一个保留原始数据,另一个保留过滤数据,最初我将原始数据分配给过滤数据,然后一旦用户输入,在搜索功能中我将与原始数据和使用搜索结果更新过滤数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多