king
2021-02-02 316877c1d9e5b6d92334f30b03d97d7e833cd934
src/menu/components/code/sandbox/codecontent/index.jsx
New file
@@ -0,0 +1,88 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { Empty, message } from 'antd'
import './index.scss'
class BraftContent extends Component {
  static propTpyes = {
    name: PropTypes.string,
    html: PropTypes.any,
    css: PropTypes.any,
    js: PropTypes.any,
  }
  state = {
    csselement: null
  }
  UNSAFE_componentWillMount () {
    const { css } = this.props
    if (css) {
      // let style = css.replace(/^[^}{]*{|}[^}{]*{/ig, (word) => {
      //   return word.replace(/}\n*/ig, `}\n#${mark}`).replace(/,/ig, `,#${mark} `)
      // })
      // style = `\n/* 自定义 */\n#${mark} ${style}\n`
      let ele = document.createElement('style')
      ele.innerHTML = css
      document.getElementsByTagName('head')[0].appendChild(ele)
      // document.getElementsByTagName('head')[0].prepend(ele)
      this.setState({csselement: ele})
    }
  }
  componentDidMount () {
    const { js, name } = this.props
    if (js) {
      try {
        // eslint-disable-next-line no-eval
        eval(js)
      } catch {
        message.warning(name + 'JS 执行失败!')
      }
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.css !== nextProps.css) {
      const { csselement } = this.state
      if (csselement && csselement.remove) {
        csselement.remove()
      }
      if (nextProps.css) {
        let ele = document.createElement('style')
        ele.innerHTML = nextProps.css
        document.getElementsByTagName('head')[0].appendChild(ele)
        this.setState({csselement: ele})
      }
    }
    if (this.props.html !== nextProps.html || this.props.js !== nextProps.js) {
      if (nextProps.js) {
        try {
          // eslint-disable-next-line no-eval
          eval(nextProps.js)
        } catch {
          message.warning(nextProps.name + 'JS 执行失败!')
        }
      }
    }
  }
  render() {
    const { html } = this.props
    if (!html) return <Empty style={{padding: '10px 0px'}} description={null}/>
    return (
      <div dangerouslySetInnerHTML={{ __html: html }}></div>
    )
  }
}
export default BraftContent