Initiate a Draft.js Editor with unordered list

2019-07-21 22:10发布

问题:

I have an array of string that I want to pre-populate a draft.js editor with as an unordered list. Here's the code:

const content = ContentState.createFromText(input.join('*'), '*')
const editorState = EditorState.createWithContent(content)
this.setState({ 
  editorState: RichUtils.toggleBlockType(editorState, 'unordered-list-item'
})

This is only created a bullet point item for the first entry in the array but the other items are not inheriting the blockstyle.

Any ideas?

回答1:

You can create array of ContentBlocks with constructor new ContentBlock(). And generate initial editor state with ContentState.createFromBlockArray. Look at this jsfiddle - http://jsfiddle.net/levsha/uy04se6r/

constructor(props) {
  super(props);
  const input = ['foo', 'bar', 'baz'];

  const contentBlocksArray = input.map(word => {
    return new ContentBlock({
      key: genKey(),
      type: 'unordered-list-item',
      characterList: new List(Repeat(CharacterMetadata.create(), word.length)),
      text: word
    });
  });

  this.state = {
    editorState: EditorState.createWithContent(ContentState.createFromBlockArray(contentBlocksArray))
  };
}