无法在React组件附带的富文本编辑器(react-draft-wysiwyg)中获取输入的数据

时间:2019-08-18 12:23:27

标签: reactjs draftjs react-draft-wysiwyg

我正在创建一个带有富文本编辑器的React组件。我选择react-draft-wysiwyg进行编辑或创建文本,然后发送到服务器。 我将仅在代码中提供引起麻烦的功能。我使用axios发送请求。 由于某些原因,我在发送POST请求时无法从表单中获取正确的数据。 我使用以下命令进行了检查:

console.log(data);
console.log(this.state.editorState);

但是现在在表单中键入了文本。我想弄清楚,谢谢大家!

代码如下:

import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import '../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import axios from 'axios';

class AddPost extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const data = {
      content: this.state.editorState
    };

    axios.post('http://localhost:5555/posts', {data})
      .then(res => {
        console.log(data);
      })

    this.setState({editorState: EditorState.createEmpty()})
  }
  render() {
    return (
      <div>
        <h5>Create document</h5>        
          <Editor
            editorState={this.state.editorState}
            wrapperClassName="demo-wrapper"
            editorClassName="demo-editor"
            onEditorStateChange={this.onEditorStateChange}
          />
          <button onClick={this.handleSubmit} className="btn-large waves-effect waves-light xbutton">Save</button>        
      </div>
    );
  }
}

export default AddPost;

1 个答案:

答案 0 :(得分:1)

要从草稿js编辑器获取数据,您需要使用

this.state.editorState.getCurrentContent().getPlainText();