通过字母搜索输入? indexOf也许?

时间:2018-11-18 21:16:20

标签: javascript reactjs

this.state = {
  text: ''
};

onChange(e) {
this.setState({text: e.target.value});
};

render() {
const { selectRate } = this.props.selectRate;
const { errors, click } = this.state;

//Filter Rate(s)
let arr = [];
if (!isEmpty(selectRate)) {
  for (let i = 0; i < selectRate.length; i++) {
    const element = selectRate[i];
    arr.push({ id: i, name: element })
  }
}

console.log(arr) 返回

  10: {id: 10, name: "PHP"}
  11: {id: 11, name: "HRK"}
  12: {id: 12, name: "NOK"}
  13: {id: 13, name: "ZAR"}
  14: {id: 14, name: "MXN"}
  15: {id: 15, name: "AUD"}
  16: {id: 16, name: "USD"}

const list = arr.filter(search(this.state.text)).map(i => <option key={i.name}>{i.name}</option>)

return (
  <div>
    <form onSubmit={this.onSubmit}>
      <input
        autoComplete='off'
        type='search'
        list='list'
        name='text'
        value={this.state.text}
        onChange={this.onChange}
        error = {errors}
      />
      <datalist id='list'>
        {list}
      </datalist>
      <button
        type='submit'
        >Search</button>
    </form>
  </div>
)
}
}

export default SearchBar;

function search(a) {
  return function(b) {
  return b.name.toUpperCase().includes(a.toUpperCase()) || !a;
  }
}

它返回所有“字符串”,包括您在输入中输入的内容。 我不明白如何使只返回第一个字母 例如: 如果您键入U,则应仅返回以U开头的“字符串”,而不返回其中包含U的字符串

1 个答案:

答案 0 :(得分:0)

您的search函数当前执行以下操作:

return b.name.toUpperCase().includes(a.toUpperCase()) || !a;

您需要做的所有事情就是将includes测试(检查字符串是否包含在任何地方)更改为startsWith测试(检查干草堆是否始于针):

return b.name.toUpperCase().startsWith(a.toUpperCase()) || !a;

请注意,startsWith是ES6函数,要支持较旧的浏览器,请改用polyfill或indexOf

return b.name.toUpperCase().indexOf(a.toUpperCase()) === 0 || !a;

因为您已经在使用ES6语法,所以可以通过使用箭头函数和隐式返回使search函数更加简洁:

const search = a => b => b.name.toUpperCase().startsWith(a.toUpperCase()) || !a;