我使用draft.js编辑器创建和更新帖子。请告诉我如何在draft.js编辑器中从HTML呈现文本。 我尝试使用renderHTML,并收到错误
“未定义'editorState'为un-undef”
没有renderHTML函数,我在编辑器中获取带有标签的HTML。 请告诉我,如何配置组件以呈现“正确的HTML”?
这里是清单:
import React, { Component } from 'react';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { EditorState, getCurrentContent, getPlainText, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import '../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { stateToHTML } from 'draft-js-export-html';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';
import renderHTML from 'react-render-html';
const updateMutation = gql`
mutation UpdateHeroMutation($id: ID!, $title: String!, $description: String!, $date: String!) {
updateHero(heroUpdate: {_id: $id, title: $title, description: $description, date: $date}) {
_id
title
description
date
}
}
`;
class Hero extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
setDate: new Date(),
editorState: EditorState.createWithContent(ContentState.createFromText(renderHTML(props.data.description)))
};
}
onChange(e) {
this.setState({ title: e.target.value })
}
onChangeSelect(published) {
this.setState({ setDate: published })
}
onEditorStateChange = (editorState) => {
this.setState({
editorState
});
}
render() {
return (
<>
<div className="label-section">Название:</div>
<h5>
<input name="title" id="title" type="text" defaultValue={this.props.data.title} onChange={e => this.onChange(e)} />
</h5>
<br />
<div className="label-section">Дата публикации:</div>
<DatePicker
id="published"
name="published"
defaultValue=""
selected={this.state.setDate}
onChange={published => this.onChangeSelect(published)}
/>
<div className="label-section">Редактировать текст:</div>
<Editor
editorState={this.state.editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
/>
<input type="text" className="hidden" defaultValue={this.props.data._id} />
<Mutation mutation={updateMutation} variables={{ id: this.props.data._id, title: this.state.title, description: stateToHTML(this.state.editorState.getCurrentContent()), date: this.state.setDate }}>
{updateHero => (
<button onClick={updateHero} type="submit">OK</button>
)}
</Mutation>
</>
);
}
}
export default Hero;
将非常感谢您的帮助!
答案 0 :(得分:2)
尝试使用draft-js-import-html代替react-render-html
import React, { Component } from 'react'
import { EditorState } from 'draft-js'
import { stateFromHTML } from 'draft-js-import-html'
class Hero extends Component {
...
constructor(props) {
this.state = {
editorState: EditorState.createWithContent(stateFromHTML(props.data.description))
}
}
...
}