Draft.js自定义内容块不会显示

时间:2017-10-01 23:15:47

标签: javascript draftjs

我是从以编程方式创建的块数组创建ContentState,但是当我使用ContentState创建一个EditorState时,没有任何内容显示在edtior中,这是创建自定义块的正确方法吗?

const dummyBlocks = [ new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: "This is a test block 1",
  characterList: List()

}), new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: "This is a test block 2",
  characterList: List()

})];

const cs = ContentState.createFromBlockArray(dummyBlocks);

const es = EditorState.createWithContent(cs);

1 个答案:

答案 0 :(得分:0)

当您手动创建块时,您需要将List传递给characterList,其长度与您正在创建的块文本的长度相符。

因此,代替characterList: List()您需要的内容将更像这样:

const charData = CharacterMetadata.create();
const firstText = "This is a test block 1";
const secondText = "This is a test block 2";
const dummyBlocks = [ new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: firstText,
  characterList: List(Repeat(charData, firstText.length))

}), new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: secondText,
  characterList: List(Repeat(charData, secondText.length))

})];

您可以在此处详细了解CharacterMetadatahttps://draftjs.org/docs/api-reference-character-metadata.html#content

这直接受到草稿AtomicBlockUtils的启发,你可以在这里找到:https://github.com/facebook/draft-js/blob/514490b1322e1c123524eae97d4aea25b4da16ce/src/model/modifier/AtomicBlockUtils.js#L66