Draftjs v0.10版本包括了一个用于管理DraftEntity数据的API变更;全局“DraftEntity”模块被弃用,DraftEntity实例将作为ContentState的一部分进行管理。这意味着以前在DraftEntity上访问的方法现在被移动到ContentState记录中。
这个API的改进为v0.11提供了许多好处:
DraftEntity Instance和storage将是immutable的。DraftEntity不会再在全局被访问到。- 对实体数据的任何更改都将触发重新渲染。
Quick Overview(快速概述)
这里是一个简单的列表表示新版已经改变了什么,以及如何更新你的应用程序:
Creating an entity(创建实体)
旧的语法
const entityKey = Entity.create(urlType, 'IMMUTABLE', {src: urlValue});
新的语法
const contentStateWithEntity = contentState.createEntity(urlType, 'IMMUTABLE', {src: urlValue,});const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
Getting an Entity(获取实体)
旧的语法
const entityInstance = Entity.get(entityKey);// entityKey is a string key associated with that entity when it was created
新的语法
const entityInstance = contentState.getEntity(entityKey);// entityKey is a string key associated with that entity when it was created
Decorator Strategy arguments change(装饰器策略参数改变)
旧的语法
const compositeDecorator = new CompositeDecorator([{strategy: (contentBlock, callback) =>exampleFindTextRange(contentBlock, callback),component: ExampleTokenComponent,},]);
新的语法
const compositeDecorator = new CompositeDecorator([{strategy: (contentBlock, callback, contentState) => (contentBlock, callback, contentState),component: ExampleTokenComponent,},]);
注意,ExampleTokenComponent将接受contentState作为一个props传递进来。
为什么现在装饰器(decorator)的策略中想要把contentState传递过去呢?因为如果我们的策略是在contentBlock中找到某些实体,我们可能需要它:
const mutableEntityStrategy = function(contentBlock, callback, contentState) {contentBlock.findEntityRanges(character => {const entityKey = character.getEntity();if (entityKey === null) {return false;}// To look for certain types of entities,// or entities with a certain mutability,// you may need to get the entity from contentState.// In this example we get only mutable entities.return contentState.getEntity(entityKey).getMutability() === 'MUTABLE';}, callback);};
Decorator Strategies that find Entities(查找实体的装饰器策略)
旧的语法
function findLinkEntities(contentBlock, callback) {contentBlock.findEntityRanges(character => {const entityKey = character.getEntity();return entityKey !== null && Entity.get(entityKey).getType() === 'LINK';}, callback);}
新的语法
function findLinkEntities(contentBlock, callback, contentState) {contentBlock.findEntityRanges(character => {const entityKey = character.getEntity();return (entityKey !== null &&contentState.getEntity(entityKey).getType() === 'LINK');}, callback);}
More Information(更多信息)
有关更多信息,请参见更新的示例。
