Skip to content

Instantly share code, notes, and snippets.

@otakustay
Created November 13, 2017 06:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otakustay/1cd993b1b6b79e09426847d7d8819603 to your computer and use it in GitHub Desktop.
Save otakustay/1cd993b1b6b79e09426847d7d8819603 to your computer and use it in GitHub Desktop.
Usage of key in react

功能比较简单,从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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment