在draftjs编辑器中显示图像

时间:2017-06-18 06:29:28

标签: javascript reactjs draftjs

我正在使用draftjs编辑器。我可以渲染内容,但我无法显示图像。使用draftjs时如何显示图像?现在只显示网址而不是图像。服务器发送数据如下

  

img src =" http:// image_url" style =" argin:30px auto;最大宽度:350px;"

抱歉,我无法使用img标签html方式,因此排除了标记语法。

function findImageEntities(contentBlock, callback, contentState) {
  contentBlock.findEntityRanges(character => {
    const entityKey = character.getEntity();
    return (
      entityKey !== null &&
      contentState.getEntity(entityKey).getType() === "IMAGE"
    );
  }, callback);
}

const Image = props => {
  const { height, src, width } = props.contentState
    .getEntity(props.entityKey)
    .getData();
  return <img src={src} height={height} width={width} />;
};
class AdminEditor extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
      editorContent: undefined,
      contentState: "",
      touched: false
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.htmlMarkup !== this.props.htmlMarkup) {
      const content = nextProps.htmlMarkup;
      const blocksFromHTML = convertFromHTML(content);
      const plainState = ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap
      );
      this.setState(state => ({
        editorState: EditorState.createWithContent(plainState, decorator)
      }));
    }
  }

  onEditorStateChange = editorState => {
    this.setState({
      editorState
    });
  };

  onEditorChange = editorContent => {
    this.setState({
      editorContent
    });
  };

  handleChange = event => {
    this.props.setEditorState(
      this.state.editorState.getCurrentContent().hasText() && this.state.touched
    );
  };

  render() {
    const { editorState } = this.state;
    const { stateOfEditor } = this.props;
    return (
      <div>
        <Editor
          tabIndex={0}
          editorState={editorState}
          initialContentState={this.props.htmlMarkup}
          toolbarClassName="home-toolbar"
          onEditorStateChange={this.onEditorStateChange}
          toolbar={{
            history: { inDropdown: true },
            inline: { inDropdown: false },
            link: { showOpenOptionOnHover: true },
            image: {
              uploadCallback: this.imageUploadCallBack,
              defaultSize: { height: "auto", width: "50%" }
            }
          }}
          onContentStateChange={this.onEditorChange}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}

export default AdminEditor;

装饰器的精确副本位于findImageEntities的顶部,我没有粘贴它只是为了减少代码行数

1 个答案:

答案 0 :(得分:0)

我看到道具onEditorStateChange = {this.onEditorStateChange}。我怀疑你是否正在使用draft-js-wysiwyg而不是draft-js。 在draft-js-wysiwyg中,你可以访问: https://github.com/jpuri/react-draft-wysiwyg/issues/589