|
| 1 | +import React, {Component} from 'react' |
| 2 | +import PropTypes from 'prop-types' |
| 3 | +import {FormControl} from 'react-bootstrap' |
| 4 | +import Stackedit from 'stackedit-js' |
| 5 | +import css from './index.css' |
| 6 | + |
| 7 | +export default class TextareaWithPreview extends Component { |
| 8 | + constructor(props) { |
| 9 | + super(props) |
| 10 | + |
| 11 | + this.state = { |
| 12 | + value: props.value |
| 13 | + } |
| 14 | + |
| 15 | + this.inputRef = (ref, ...params) => { |
| 16 | + this.ref = ref |
| 17 | + if (this.props.inputRef) { |
| 18 | + this.props.inputRef(ref, ...params) |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + componentWillReceiveProps(nextProps) { |
| 24 | + if (nextProps.value !== this.state.value) { |
| 25 | + this.setState({ value: nextProps.value }) |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + enterPreviewMode() { |
| 30 | + const editor = this._editor = this._editor || new Stackedit() |
| 31 | + editor.openFile({ |
| 32 | + content: { |
| 33 | + text: this.state.value, |
| 34 | + } |
| 35 | + }) |
| 36 | + |
| 37 | + // Listen to StackEdit events and apply the changes to the textarea. |
| 38 | + editor.off('fileChange') |
| 39 | + editor.on('fileChange', (file) => { |
| 40 | + this.setState({ |
| 41 | + value: file.content.text, |
| 42 | + }) |
| 43 | + }) |
| 44 | + |
| 45 | + |
| 46 | + editor.off('close') |
| 47 | + editor.on('close', () => this.ref.focus()) |
| 48 | + } |
| 49 | + |
| 50 | + render() { |
| 51 | + return ( |
| 52 | + <div className={css.textareaWrapper}> |
| 53 | + <FormControl {...this.props} value={this.state.value} componentClass="textarea" inputRef={this.inputRef.bind(this)}/> |
| 54 | + <div onClick={this.enterPreviewMode.bind(this)} title="预览" className={css.preview}><span className="glyphicon glyphicon-fullscreen" aria-hidden="true"></span></div> |
| 55 | + </div> |
| 56 | + ) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +TextareaWithPreview.propTypes = { |
| 61 | + value: PropTypes.any, |
| 62 | + inputRef: PropTypes.func |
| 63 | +} |
| 64 | + |
0 commit comments