本章讨论实体(Entities)系统,Draft用来注解文本的元数据类型,图片链接,视频在Draft这里都算是实体。原文如下:
This article discusses the Entity system, which Draft uses for annotating ranges of text with metadata. Entities enable engineers to introduce levels of richness beyond styled text to their editors. Links, mentions, and embedded content can all be implemented using entities.
In the Draft repository, the link editor and entity demo provide live code examples to help clarify how entities can be used, as well as their built-in behavior.
The Entity API Reference provides details on the static methods to be used when creating, retrieving, or updating entity objects.
概念知识点
An entity is an object that represents metadata for a range of text within a Draft editor. It has three properties:
实体有三种属性:
type: A string that indicates what kind of entity it is, e.g. ‘LINK’, ‘MENTION’, ‘PHOTO’.
类型:实体所属类型
mutability: Not to be confused with immutability a la immutable-js, this property denotes the behavior of a range of text annotated with this entity object when editing the text range within the editor. This is addressed in greater detail below.
可变性:是否可以修改
- data: An optional object containing metadata for the entity. For instance, a ‘LINK’ entity might contain a data object that contains the href value for that link.
All entities are stored in a single object store within the Entity module, and are referenced by key within ContentState and React components used to decorate annotated ranges. (We are considering future changes to bring the entity store into EditorState or ContentState.)
数据:可选项,即数据关联,如超链接关联网址
Using decorators or custom block components, you can add rich rendering to your editor based on entity metadata.
使用装饰器(decorators)和自定义块组件( custom block components),可以自己丰富自己的编辑器
创建实体
使用Entity.create
创建实体,接受三个上述的参数,该方法返回一个key字符串,可以用来管理这个实体,当把实体添加到编辑内容时需要用到这个key。Modifier(后面将会提到)模块就包含一个applayEntity。
const key = Entity.create('LINK', 'MUTABLE', {href: 'http://www.zombo.com'});
const contentStateWithLink = Modifier.applyEntity(
contentState,
targetRange,
key
);
对于给定的文本,你可以通过实体key 使用getEntityAt()
从ContentBlock
对象提取到关联实体,并可以获取其data。
const blockWithLinkAtBeginning = contentState.getBlockForKey('...');
const linkKey = blockWithLinkAtBeginning.getEntityAt(0);
const linkInstance = Entity.get(linkKey);
const {href} = linkInstance.getData();
概念:”Mutability”
Entities may have one of three “mutability” values. The difference between them is the way they behave when the user makes edits to them.
实体有三种值,取决于如何编辑他们
Note that DraftEntityInstance objects are always immutable Records, and this property is meant only to indicate how the annotated text may be “mutated” within the editor. (Future changes may rename this property to ward off potential confusion around naming.)
Immutable
不可编辑,只能整体移除,比如提及的名字,不可编辑
This text cannot be altered without removing the entity annotation from the text. Entities with this