searchbar.jsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * @author oldj
  3. * @blog http://oldj.net
  4. */
  5. 'use strict'
  6. import React from 'react'
  7. import { Input, Icon } from 'antd'
  8. import Agent from '../Agent'
  9. import './searchbar.less'
  10. export default class SearchBar extends React.Component {
  11. constructor (props) {
  12. super(props)
  13. this.state = {
  14. show: false,
  15. keyword: ''
  16. }
  17. this._t = null
  18. Agent.on('search_on', () => {
  19. this.setState({
  20. show: true
  21. }, () => {
  22. setTimeout(() => {
  23. this.el_keyword.focus()
  24. }, 100)
  25. })
  26. })
  27. Agent.on('search_off', () => {
  28. this.clearSearch()
  29. })
  30. }
  31. clearSearch () {
  32. this.setState({
  33. show: false,
  34. keyword: ''
  35. })
  36. Agent.emit('search', '')
  37. }
  38. emptySearch () {
  39. this.setState({keyword: ''})
  40. Agent.emit('search', '')
  41. this.el_keyword.focus()
  42. }
  43. onBlur () {
  44. if (!this.state.keyword) {
  45. this.clearSearch()
  46. this.onCancel()
  47. }
  48. }
  49. doSearch (kw) {
  50. this.setState({
  51. keyword: kw
  52. })
  53. clearTimeout(this._t)
  54. this._t = setTimeout(() => {
  55. Agent.emit('search', kw)
  56. }, 300)
  57. }
  58. onCancel () {
  59. Agent.emit('cancel_search')
  60. }
  61. render () {
  62. if (!this.state.show) {
  63. return null
  64. }
  65. return (
  66. <div id="sh-searchbar">
  67. <Input
  68. ref={c => this.el_keyword = c}
  69. size="large"
  70. //placeholder="keyword"
  71. suffix={this.state.keyword ? <Icon type="close-circle" onClick={this.emptySearch.bind(this)}/> : null}
  72. value={this.state.keyword}
  73. onBlur={this.onBlur.bind(this)}
  74. onChange={(e) => this.doSearch(e.target.value)}
  75. onKeyDown={(e) => (e.keyCode === 27 && this.onCancel())}
  76. />
  77. </div>
  78. )
  79. }
  80. }