keyword.jsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import React from 'react';
  2. import {Tag,Input,Button,Tooltip} from 'antd';
  3. const KeyWordTagGroup = React.createClass({
  4. getInitialState() {
  5. return {
  6. tags: [],
  7. inputVisible: false,
  8. inputValue: ''
  9. };
  10. },
  11. handleClose(removedTag) {
  12. const tags = this.state.tags.filter(tag => tag !== removedTag);
  13. this.props.tagsArr(tags);
  14. this.setState({ tags });
  15. },
  16. showInput() {
  17. this.setState({ inputVisible: true }, () => this.input.focus());
  18. },
  19. handleInputChange(e) {
  20. this.setState({ inputValue: e.target.value });
  21. },
  22. handleInputConfirm() {
  23. const state = this.state;
  24. const inputValue = state.inputValue;
  25. let tags = state.tags;
  26. if (inputValue && tags.indexOf(inputValue) === -1 && inputValue.replace(/(^\s*)|(\s*$)/g, "").length != 0) {
  27. tags = [...tags, inputValue.replace(/(^\s*)|(\s*$)/g, "")];
  28. }
  29. this.props.tagsArr(tags);
  30. this.setState({
  31. tags,
  32. inputVisible: false,
  33. inputValue: '',
  34. });
  35. },
  36. componentWillMount() {
  37. this.state.tags = this.props.keyWordArr;
  38. },
  39. componentWillReceiveProps(nextProps) {
  40. if (this.props.keyWordArr != nextProps.keyWordArr) {
  41. this.state.tags = nextProps.keyWordArr;
  42. };
  43. },
  44. render() {
  45. const { tags, inputVisible, inputValue } = this.state;
  46. return (
  47. <div className="keyWord-tips">
  48. {tags.map((tag, index) => {
  49. const isLongTag = tag.length > 10;
  50. const tagElem = (
  51. <Tag key={tag} closable={index !== -1} afterClose={() => this.handleClose(tag)}>
  52. {isLongTag ? `${tag.slice(0, 10)}...` : tag}
  53. </Tag>
  54. );
  55. return isLongTag ? <Tooltip title={tag}>{tagElem}</Tooltip> : tagElem;
  56. })}
  57. {inputVisible && (
  58. <Input
  59. ref={input => this.input = input}
  60. type="text"
  61. style={{ width: 78 }}
  62. value={inputValue}
  63. onChange={this.handleInputChange}
  64. onBlur={this.handleInputConfirm}
  65. onPressEnter={this.handleInputConfirm}
  66. />
  67. )}
  68. {!inputVisible && <Button className="addtips" type="dashed" disabled={tags.length > 9 ? true : false} onClick={this.showInput}>+ 新关键词</Button>}
  69. </div>
  70. );
  71. }
  72. });
  73. export default KeyWordTagGroup;