我正在创建一个包含富文本编辑器的 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;