draftjs如何使用内容

时间:2016-03-09 06:02:32

标签: reactjs draftjs

偶然发现这个很酷的文本编辑器,facebook的draft.js。 我尝试按照github中的示例进行操作,但我想创建一个内容编辑器而不是空编辑器。

var EditorState = Draft.EditorState;

var RichEditor = React.createClass({
   getInitialState(){
      return {editorState: EditorState.createWithContent("Hello")}
      //the example use this code to createEmpty editor
     // return ({editorState: EditorState.createEmpty()})
   }
});

运行它,但是我得到错误说"未捕获TypeError:contentState.getBlockMap不是函数"

8 个答案:

答案 0 :(得分:35)

EditorState.createWithContent的第一个参数是ContentState,而不是字符串。您需要导入ContentState

var EditorState = Draft.EditorState;
var ContentState = Draft.ContentState;

使用ContentState.createFromText并将结果传递给EditorState.createWithContent

return {
  editorState: EditorState.createWithContent(ContentState.createFromText('Hello'))
};

答案 1 :(得分:25)

我为DraftJS创建了一组包,以帮助导入和导出内容(HTML / Markdown)。我在我的项目react-rte中使用了这些。您可能正在寻找的是:draft-js-import-html在npm。

npm install draft-js-import-html

您可以如何使用它的示例:

var stateFromHTML = require('draft-js-import-html').stateFromHTML;
var EditorState = Draft.EditorState;

var RichEditor = React.createClass({
  getInitialState() {
    let contentState = stateFromHTML('<p>Hello</p>');
    return {
      editorState: EditorState.createWithContent(contentState)
    };
  }
});

我发布的模块是:

答案 2 :(得分:8)

有一些API更改,为清楚起见,这些示例使用最新的API v0.10.0

有很多方法,但基本上你有三个选项,具体取决于你是否要使用纯文本,样式文本或html标记作为内容资源。

明文是明显的,但对于样式文本,您需要使用序列化的javasript对象或html标记。

让我们从纯文本示例开始:

import {Editor, EditorState} from 'draft-js';

class MyEditor extends Component{

  constructor(props) {
    super(props);

    const plainText = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
    const content = ContentState.createFromText(plainText);

    this.state = { editorState: EditorState.createWithContent(content)};

    this.onChange = (editorState) => {
      this.setState({editorState});
    }
  }
  render(){
    return(
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    )
  }
}

为了导入样式内容,Draft.js提供了convertFromRawconvertFromHTML实用程序功能。

convertFromRaw函数将原始javascript对象作为参数。在这里,我们使用JSON字符串化的javascript对象作为内容源:

class MyEditor extends Component{

  constructor(props) {
    super(props);

    const rawJsText = `{
      "entityMap": {},
      "blocks": [
        {
          "key": "e4brl",
          "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
          "type": "unstyled",
          "depth": 0,
          "inlineStyleRanges": [
            {
              "offset": 0,
              "length": 11,
              "style": "BOLD"
            },
            {
              "offset": 28,
              "length": 29,
              "style": "BOLD"
            },
            {
              "offset": 12,
              "length": 15,
              "style": "ITALIC"
            },
            {
              "offset": 28,
              "length": 28,
              "style": "ITALIC"
            }
          ],
          "entityRanges": [],
          "data": {}
        },
        {
          "key": "3bflg",
          "text": "Aenean commodo ligula eget dolor.",
          "type": "unstyled",
          "depth": 0,
          "inlineStyleRanges": [],
          "entityRanges": [],
          "data": {}
        }
      ]
    }`;

    const content  = convertFromRaw(JSON.parse(rawJsText));
    this.state = { editorState: EditorState.createWithContent(content)};

    this.onChange = (editorState) => {
      this.setState({editorState});
    }
  }
  render(){
    return(
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    )
  }
}

Draft.js提供convertToRaw函数,以便您可以将编辑器的状态转换为原始javascript对象以进行长期存储。

最后,在这里你是如何用html标记做的:

class MyEditor extends Component{

  constructor(props) {
    super(props);

    const html = `<p>Lorem ipsum <b>dolor</b> sit amet, <i>consectetuer adipiscing elit.</i></p>
      <p>Aenean commodo ligula eget dolor. <b><i>Aenean massa.</i></b></p>`;

      const blocksFromHTML = convertFromHTML(html);
      const content = ContentState.createFromBlockArray(
        blocksFromHTML.contentBlocks,
        blocksFromHTML.entityMap
      );

    this.state = { editorState: EditorState.createWithContent(content)};

    this.onChange = (editorState) => {
      this.setState({editorState});
    }
  }
  render(){
    return(
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
      />
    )
  }
}

答案 3 :(得分:6)

您可以使用convertFromHTML导入带有createWithContent

的html
import { convertFromHTML, ContentState } from 'draft-js'

const html = '<div><p>hello</p></div>'
const blocksFromHTML = convertFromHTML(html)
const content = ContentState.createFromBlockArray(blocksFromHTML)
this.state = { 
  editorState: EditorState.createWithContent(content)
}

如草稿convertFromHtml example所示。请注意,0.9.1版本无法导入图片,而0.10.0可以。

0.10.0 createFromBlockArray更改为:

const content = ContentState.createFromBlockArray(
  blocksFromHTML.contentBlocks,
  blocksFromHTML.entityMap
)

答案 4 :(得分:1)

我发现这是一种干净的功能丰富的做事方式。您可以在以后添加更多插件,将内容导出为$start_date = Carbon::create( $request->start_year, $request->start_month, $request->start_day ); $start_date->setTimeFromTimeString( $request->start_time ); $finish_date = Carbon::create( $request->finish_year, $request->finish_month, $request->finish_day ); $finish_date->setTimeFromTimeString( $request->finish_time ); 等,而无需更改组件的结构。

.md

答案 5 :(得分:1)

当您需要使用纯文本启动编辑器时。

使用EditorState.createWithContentContentState.createFromText方法。工作示例 - https://jsfiddle.net/levsha/3m5780jc/

button.setOnClickListener {  
 // You code here
}

当您需要使用html标记字符串中的内容启动编辑器时。

使用convertFromHTMLContentState.createFromBlockArray。工作示例 - https://jsfiddle.net/levsha/8aj4hjwh/

constructor(props) {
  super(props);

  const initialContent = 'Some text';
  const editorState = EditorState.createWithContent(ContentState.createFromText(initialContent));

  this.state = {
    editorState
  };
}

如果您有一个字符串数组,并且想要使用某些默认的draft.js块类型启动编辑器。

您可以使用构造函数constructor(props) { super(props); const sampleMarkup = ` <div> <h2>Title</h2> <i>some text</i> </div> `; const blocksFromHTML = convertFromHTML(sampleMarkup); const state = ContentState.createFromBlockArray( blocksFromHTML.contentBlocks, blocksFromHTML.entityMap ); this.state = { editorState: EditorState.createWithContent(state), }; } 创建ContentBlocks的数组,并将其传递给new ContentBlock(...)方法。使用ContentState.createFromBlockArray - https://jsfiddle.net/levsha/uy04se6r/

的工作示例
unordered-list-item

当您需要使用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)) }; } 原始JS结构的内容启动编辑器时。

如果您以前使用convertToRaw将内容状态保存到原始JS结构(有关详细信息,请阅读this answer)。您可以使用convertFromRaw方法启动编辑器。工作示例 - https://jsfiddle.net/levsha/tutc419a/

ContentState

答案 6 :(得分:1)

简单中,您可以从一开始就设置原始HTML内容到编辑器,也可以随时使用setState,如下所示。

editorState: EditorState.createWithContent(ContentState.createFromBlockArray(convertFromHTML('<b>Program</b>')))

导入必要的组件。

import { EditorState, ContentState, convertFromHTML } from 'draft-js'

答案 7 :(得分:0)

如果要使用HTML格式设置,只需添加以下代码即可将edtitorState设置为初始值

this.state = {
  editorState: EditorState.createWithContent(
    ContentState.createFromBlockArray(
      convertFromHTML('<p>My initial content.</p>')
    )
  ),
}
相关问题