【发布时间】:2019-04-19 22:16:56
【问题描述】:
我的 React 应用程序中有一个评论框,我使用 Draft.js 构建它,如下所示。我输入一些文本并使用粗体和斜体按钮对其进行格式化。然后我点击评论按钮。单击 Comment 按钮后,将触发 sendUserComment 函数并更新状态“newComment”。 AXIOS 会将它们发送到数据库并返回评论,以便我可以在“newCommentShow”div 中显示评论。
问题是,如果我将评论输入为文本并应用粗体,数据将被发送到数据库中
<p><b>Some texts</b></p>
并且返回的数据以相同的方式处理。 所以我将整个<p><b>Some texts</b></p> 视为'newCommentShow' div 中的字符串。如何处理该字符串中的标签并显示正确的格式文本?
const { Toolbar } = toolbarPlugin;
const plugins = [toolbarPlugin];
const text = '';
class ProjectModal extends Component {
constructor(props) {
super(props);
this.state = {
newComment: '',
editorState: createEditorStateWithText(text)
};
this.editorOnChange = this.editorOnChange.bind(this);
}
editorOnChange(editorState) {
this.setState({ editorState });
}
sendUserComment = () => {
const com = stateToHTML(this.state.editorState.getCurrentContent())
API.post('add_comment', com)
.then(({ data }) => {
console.log(data);
this.setState({ newComment: data.comment })
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
}
render() {
return(
<div className="newCommentBox">
<div className="newCommentMain">
<Toolbar>
{
(externalProps) => (
<div className="toolbarModal">
<BoldButton {...externalProps} />
<ItalicButton {...externalProps} />
</div>
)
}
</Toolbar>
<Editor
editorState={this.state.editorState}
onChange={this.editorOnChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
className="editor"
/>
</div>
<button className="commentBtn" onClick={() => this.sendUserComment}>Comment</button>
<div className="newCommentShow">{this.state.newComment}</div>
</div>
)
}
}
【问题讨论】:
标签: javascript reactjs