简体   繁体   English

自动完成功能可以在单词的任何位置匹配模式,只能在开始时匹配吗?

[英]Autocomplete is matching to pattern anywhere in words, can it match only at the start?

I am using an autocomplete for an input box based on the answer provided to question: https://stackoverflow.com/a/35429210/11082818 . 我正在根据提供给问题的答案对输入框使用自动完成功能: https : //stackoverflow.com/a/35429210/11082818

The autocomplete looks to match the input to a pattern in the key 'street' in a JSON.This autocomplete works, however, it matches to a pattern anywhere in the autosuggest words. 自动完成功能看起来可以将输入与JSON的键``street''中的模式匹配。此自动完成功能可以工作,但是可以与自动建议单词中的任何位置的模式匹配。

For example: If the user types "dale" it will suggest both "Cransdale Street" and "Wensleydale Street". 例如:如果用户键入“ dale”,则将同时建议“ Cransdale Street”和“ Wensleydale Street”。

I'd like to get it to only match patterns from the start of the street names. 我想让它只匹配街道名称开头的模式。 So if the user enters "dale" nothing comes up. 因此,如果用户输入“ dale”,则不会显示任何内容。 But as the user enters "Cr" then "Cransdale Street" is suggested. 但是,当用户输入“ Cr”时,建议使用“ Cransdale Street”。

This isn't an issue in such a small JSON but I have one that has 1000's objects. 在这么小的JSON中这不是问题,但是我有一个包含1000个对象的对象。

var React = require('react-native');
var {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  TextInput,
  ListView,
  View,
} = React;

var adresses = [
  {
    street: "Cransdale Street",
      city: "Sydney",
    country: "Australia"
    },{
    street: "Wensleydale Street",
      city: "Sydney",
    country: "Australia"
  }
];

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

class SampleApp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      searchedAdresses: []
    };
  };

  searchedAdresses = (searchedText) => {
    var searchedAdresses = adresses.filter(function(adress) {
      return adress.street.toLowerCase().indexOf(searchedText.toLowerCase()) > -1;
    });
    this.setState({searchedAdresses: searchedAdresses});
  };

    renderAdress = (adress) => {
    return (
      <View>
        <Text>{adress.street}, {adress.city}, {adress.country}</Text>
      </View>
    );
  };
  render() {
    return (
      <View style={styles.container}>
        <TextInput 
            style={styles.textinput}
            onChangeText={this.searchedAdresses}
            placeholder="Type your adress here" />
        <ListView
                    dataSource={ds.cloneWithRows(this.state.searchedAdresses)}
          renderRow={this.renderAdress} />
      </View>
    );
  };
}

Change 更改

return adress.street.toLowerCase().indexOf(searchedText.toLowerCase()) > -1;

to

return adress.street.toLowerCase().startsWith(searchedText.toLowerCase());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM