Link.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import Input from './Input'
  2. import React from 'react'
  3. let inputStyle = {
  4. width: '300px',
  5. }
  6. let spanStyle = {
  7. fontSize: '14px',
  8. color: 'rgba(0, 0, 0, 0.65)',
  9. display: 'inline-block',
  10. width: '80px',
  11. }
  12. let formItmeStyle = {
  13. marginBottom: '10px',
  14. }
  15. class Link extends React.Component {
  16. state = {
  17. text: '',
  18. link: '',
  19. title: '',
  20. newTab: false,
  21. showTips: false,
  22. }
  23. hasProtocol = link => {
  24. if (link.match(/^http:|https:/) || link.match(/^\/\//)) {
  25. return true
  26. }
  27. return false
  28. }
  29. generateHtml = () => {
  30. let {text, link, title, newTab} = this.state
  31. if (link) {
  32. let html = ''
  33. if (!this.hasProtocol(link)) {
  34. link = 'http://' + link
  35. }
  36. html += `<a href="${link}" target=${newTab ? '_blank' : '_self'} title="${title}">${text || link}</a>`
  37. return html
  38. }
  39. }
  40. changeConfig = (e, type) => {
  41. let value = e.target.value
  42. let boolType = ['newTab']
  43. if (boolType.indexOf(type) !== -1) {
  44. value = !!value
  45. }
  46. if (type == 'link') {
  47. if (!this.hasProtocol(value)) {
  48. this.setState({
  49. showTips: true,
  50. })
  51. } else {
  52. this.setState({
  53. showTips: false,
  54. })
  55. }
  56. }
  57. if (type == 'newTab') {
  58. return this.setState({newTab: !this.state.newTab})
  59. }
  60. this.setState({[type]: value}, () => {
  61. this.props.onChange && this.props.onChange(this.generateHtml())
  62. })
  63. }
  64. render() {
  65. let {text, link, title, newTab, showTips} = this.state
  66. return (
  67. <form>
  68. <div style={formItmeStyle}>
  69. <span style={spanStyle}>文本内容:</span>
  70. <Input type='text' style={inputStyle} value={text} onChange={e => this.changeConfig(e, 'text')} />
  71. </div>
  72. <div style={formItmeStyle}>
  73. <span style={spanStyle}>链接地址:</span>
  74. <Input type='text' style={inputStyle} value={link} onChange={e => this.changeConfig(e, 'link')} />
  75. </div>
  76. <div style={formItmeStyle}>
  77. <span style={spanStyle}>标题:</span>
  78. <Input type='text' style={inputStyle} value={title} onChange={e => this.changeConfig(e, 'title')} />
  79. </div>
  80. <div style={formItmeStyle}>
  81. <span style={{color: 'rgba(0, 0, 0, 0.65)', fontSize: '14px'}}>是否在新窗口打开:</span>
  82. <input type='checkbox' checked={newTab} onChange={e => this.changeConfig(e, 'newTab')} />
  83. </div>
  84. {showTips && <p style={{fontSize: '14px', color: 'red'}}>您输入的超链接中不包含http等协议名称,默认将为您添加http://前缀</p>}
  85. </form>
  86. )
  87. }
  88. }
  89. export default Link