功能比较简单,从URL中获取到q
参数并且显示在文本框中,但允许文本框内用户输入其它的搜索词
如果让Input
工作在受控模式下,那么就必须控制value
的同步,也需要componentWillReceiveProps
进行同步,代码较多。如果使用defaultValue
但不提供key
,则会导致URL变化后文本框内容不会更新
一个简易的方法就是使用key
来在URL变化时强制刷新文本框,但同时也能利用defaultValue
简化同步
/** | |
* @file 全局搜索顶部搜索框 | |
* @author zhanglili | |
*/ | |
import {PureComponent} from 'react'; | |
import {bind} from 'lodash-decorators'; | |
import queryString from 'query-string'; | |
import {withRouter} from 'react-router-dom'; | |
import {Input} from 'antd'; | |
import styles from './TopSearchBox.less'; | |
class TopSearchBox extends PureComponent { | |
@bind() | |
submitKeywords(value) { | |
const {location, history} = this.props; | |
const query = queryString.parse(location.search); | |
const newQuery = {...query, q: value}; | |
const newURL = location.pathname + '?' + queryString.stringify(newQuery); | |
history.push(newURL); | |
} | |
render() { | |
const {location} = this.props; | |
const {q} = queryString.parse(location.search); | |
return <Input.Search key={q} className={styles.main} defaultValue={q} onSearch={this.submitKeywords} />; | |
} | |
} | |
export default withRouter(TopSearchBox); |
/** | |
* @file 全局搜索顶部搜索框 | |
* @author zhanglili | |
*/ | |
import {PureComponent} from 'react'; | |
import {bind} from 'lodash-decorators'; | |
import queryString from 'query-string'; | |
import {withRouter} from 'react-router-dom'; | |
import {Input} from 'antd'; | |
import styles from './TopSearchBox.less'; | |
class TopSearchBox extends PureComponent { | |
constructor(props) { | |
super(props); | |
const {location} = props; | |
const {q} = queryString.parse(location.search); | |
this.state = {value: q}; | |
} | |
componentWillReceiveProps(nextProps) { | |
if (nextProps.location !== this.props.location) { | |
const {q} = queryString.parse(nextProps.location.search); | |
this.setState({value: q}); | |
} | |
} | |
@bind() | |
submitKeywords(value) { | |
const {location, history} = this.props; | |
const query = queryString.parse(location.search); | |
const newQuery = {...query, q: value}; | |
const newURL = location.pathname + '?' + queryString.stringify(newQuery); | |
history.push(newURL); | |
} | |
@bind() | |
syncValue(value) { | |
this.setState({value}); | |
} | |
render() { | |
const {value} = this.state; | |
return ( | |
<Input.Search | |
className={styles.main} | |
value={value} | |
onChange={this.syncValue} | |
onSearch={this.submitKeywords} | |
/> | |
); | |
} | |
} | |
export default withRouter(TopSearchBox); |