我正试图通过基于搜索栏文本的平面列表进行搜索.我遇到的问题是,当用户输入错误时...如果他们想输入"burger",但错误地输入了"burget",那么它将不会返回应有的结果.当用户删除"t"时,它应该再次使用与"burge"部分匹配的最后一个文本重新呈现平面列表.

注意:使用react native elements搜索栏,只需e或event即可调用文本.

到目前为止,我所拥有的一切.js文件:

searchText = (e) => {
    let text = e.toLowerCase();
    let trucks = this.state.data;

    // search by food truck name
    let filteredName = trucks.filter((truck) => {
      return truck.name.toLowerCase().match(text); 
    });

    // if no match and text is empty
    if(!text || text === '') {
      console.log('change state');
        this.setState({
          data: initial
        });
      }
    // if no name matches to text output
    else if(!Array.isArray(filteredName) && !filteredName.length) {
      console.log("not name");
      this.setState({
        data: [],
      });
    }
    // if name matches then display
    else if(Array.isArray(filteredName)) {
      console.log('Name');
      this.setState({
        data: filteredName,
      });
    }
   };

<View style={styles.container}>
  <SearchBar
    round
    lightTheme
    containerStyle={styles.search}
    ref="search"
    textInputRef="searchText"
    onChangeText={this.searchText.bind(this)}
    placeholder='Search by Truck Name...'
   />
   <TruckList getTruck={(truck) => this.setTruck(truck)} truckScreen={this.truckScreen} data={this.state.data}/>
</View>

然后是卡车司机.JS:

export default class TruckList extends Component {
    // rendering truck screen
    renderTruckScreen = (item) => {
        this.props.truckScreen();
        this.props.getTruck(item);
    }

    render() {
        return(
            <List style={styles.list}>
                <FlatList
                    data={this.props.data}
                    renderItem={({ item }) => (
                        <ListItem
                            roundAvatar
                            avatar={{uri: item.pic1}}
                            avatarStyle={styles.avatar}
                            title={item.name}
                            titleStyle={styles.title}
                            subtitle={
                                <View style={styles.subtitleView}>
                                    <Text style={styles.subtitleFood}>{item.food}</Text>
                                    <View style={styles.subtitleInfo}>
                                        <Icon 
                                            name="favorite"
                                            size={20}
                                            color={"#f44336"}
                                            style={styles.subtitleFavorite}
                                        />
                                        <Text style={styles.subtitleFavoriteText}>{item.favorited} favorited</Text>
                                    </View>
                                </View>
                            }
                            onPress={() => this.renderTruckScreen(item)}
                        />
                    )}
                    keyExtractor={(item) => item.uid}
                    ListFooterComponent={this.footer}
                />
            </List>
        )
      }
    }

我试过其他几种方法,但都没有用.此外,我在React Native上看到的唯一解决方案是ListView,它会随着时间的推移而贬值.所以我try 用新的平面列表组件来实现这一点.

谢谢你的帮助!

推荐答案

我今天在try 在新的FlatList组件上实现过滤/搜索功能时遇到了同样的问题.我就是这样解决的:

通过在父组件的状态下创建另一个名为noData的项,当没有与搜索匹配的结果时,可以将其设置为true,然后有条件地呈现平面列表.

我的实现与你的略有不同,但如果我必须调整你的代码,它会是这样的:

搜索文本功能:

searchText = (e) => {
    let text = e.toLowerCase()
    let trucks = this.state.data
    let filteredName = trucks.filter((item) => {
      return item.name.toLowerCase().match(text)
    })
    if (!text || text === '') {
      this.setState({
        data: initial
      })
    } else if (!Array.isArray(filteredName) && !filteredName.length) {
      // set no data flag to true so as to render flatlist conditionally
      this.setState({
        noData: true
      })
    } else if (Array.isArray(filteredName)) {
      this.setState({
        noData: false,
        data: filteredName
      })
    }
  }

然后将noData bool传递给卡车列表组件:

<TruckList getTruck={(truck) => this.setTruck(truck)} 
truckScreen={this.truckScreen} data={this.state.data} noData={this.state.noData}/>

然后,仅当出现以下结果时,才在TruckList组件中呈现平面列表:

<List style={styles.list}>
{this.props.noData ? <Text>NoData</Text> : <FlatList {...} />}         
</List>

这样就可以处理用户输入错误,因为一旦没有结果,它就会重新呈现平面列表,并且在删除输入错误时会记住以前的搜索状态..

如果有帮助,请告诉我!

React-native相关问答推荐

原生react :顶部的滑块位置

使用react-native-reanimatedreact 导航崩溃

导航堆栈不显示

NPM INSTALL 在 react-native 项目上失败:无法解析 react 和 react-dom 的依赖树

无法设置文本输入参考

从 .apk 到 .aab 的本地构建版本react,如何将应用程序发送给客户端?

如何在 React-Native 中创建检测自动位置的map

react-native app.js index.js

React Native 开发中的/ios/index/DataStore文件夹是什么

中彼此相邻对齐(Align) react native

React-Native Android - 找不到 com.android.tools:common

Realm 和 React Native - 实现自动更新的最佳实践?

试图注册两个同名的视图 RNGestureHandlerButton

路由状态没有通过 redux 保持在 react-native

组件div的视图配置 getter 回调必须是一个函数(收到 undefined)

带有 xcode 模拟器的 react-native 有非常慢的alert

如何将props传递给 React Navigation 导航器中的组件?

React native - 以编程方式判断是否启用了远程 JS 调试

如何升级 react-native gradle 版本

使用 TouchableWithoutFeedback react-native onPress 不起作用