【问题标题】:how to add caption to images in draft js?如何在草稿 js 中为图像添加标题?
【发布时间】:2020-10-29 11:00:42
【问题描述】:

是否可以在草稿 js 中呈现输入(用于为图像添加标题)并可以获得用户输入的数据?我熟悉“自定义块渲染”概念并遵循https://draftjs.org/docs/advanced-topics-custom-block-render-map/ 提供的说明但是,当我想在输入中写一些东西时,我遇到了以下错误:

invariant.js:40 Uncaught Invariant Violation: Unknown DraftEntity key: null.

实际上,block?.getEntityAt(0) 返回 null,因为当我开始键入时字符列表发生了变化。

这是自定义块渲染器代码:

import React from "react";
import { fromJS } from "immutable";

export const CustomBlockRenderer = (block, editorState, props) => {
  if (block.getType() === "atomic") {
    return {
      component: Media,
      editable: false,
    };
  }
  return null;
};

const Image = (props) => {
  if (!!props.src) {
    return <img src={props.src} />;
  }
  return null;
};

const Media = (props) => {
  const entity = props.contentState?.getEntity(props?.block?.getEntityAt(0));
  const { src } = entity?.getData();

  const type = entity?.getType();

  let customBlock;

  if (type === "image") {
    customBlock = (
      <figure className="custom-block__image-wrap">
        <Image src={src?.url} className="custom-block__image" />
        <figcaption className="custom-block__caption">{src?.caption}</figcaption>
      </figure>
    );
  } else {
    return null;
  }

  return customBlock;
};

【问题讨论】:

    标签: javascript reactjs draftjs


    【解决方案1】:

    我最近遇到了类似的问题。 Here 它如何工作的简化演示。请注意,draft-js 中的 EditorBlock 组件用于图像标题节点。如果您想要自定义组件内的可编辑区域,您应该在自定义组件中使用EditorBlock

    class MyCustomBlock extends React.Component {
      render() {
        const imgSrc = this.props.block.get("data").src;
    
        return (
          <div className="my-custom-block">
            <figure className="custom-block__image-wrap">
              <img src={imgSrc} className="custom-block__image" />
              <figcaption className="custom-block__caption">
                <EditorBlock {...this.props} />
              </figcaption>
            </figure>
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2017-05-25
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多