Javascript 如何在React中显示Draft.js格式化的数据?
我的React应用程序中有一个评论框,我用Draft.js构建了它,如下所示。我输入一些文本并用粗体和斜体按钮格式化它们。然后我点击评论按钮。单击“注释”按钮后,sendUserComment函数将被激发并更新状态“newComment”。AXIOS会将它们发送到数据库并返回注释,这样我就可以在“newCommentShow”div中显示注释 问题是,如果我以文本形式键入注释并应用粗体,则数据将作为Javascript 如何在React中显示Draft.js格式化的数据?,javascript,reactjs,Javascript,Reactjs,我的React应用程序中有一个评论框,我用Draft.js构建了它,如下所示。我输入一些文本并用粗体和斜体按钮格式化它们。然后我点击评论按钮。单击“注释”按钮后,sendUserComment函数将被激发并更新状态“newComment”。AXIOS会将它们发送到数据库并返回注释,这样我就可以在“newCommentShow”div中显示注释 问题是,如果我以文本形式键入注释并应用粗体,则数据将作为 一些文本 返回的数据以同样的方式进行处理因此,我将整个部分文本视为'newCommentShow
一些文本
返回的数据以同样的方式进行处理因此,我将整个部分文本
视为'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>
)
}
}
const{Toolbar}=toolbarPlugin;
const plugins=[toolbarPlugin];
常量文本=“”;
类ProjectModal扩展组件{
建造师(道具){
超级(道具);
此.state={
新成员:'',
editorState:createEditorStateWithText(文本)
};
this.editorOnChange=this.editorOnChange.bind(this);
}
编辑更改(编辑状态){
this.setState({editorState});
}
sendUserComment=()=>{
const com=stateToHTML(this.state.editorState.getCurrentContent())
API.post('add_comment',com)
。然后({data})=>{
控制台日志(数据);
this.setState({newcommon:data.comment})
})
.catch((错误)=>{
log(“AXIOS错误:”,err);
})
}
render(){
返回(
{
(外部道具)=>(
)
}
{this.editor=element;}}
className=“编辑器”
/>
this.sendUserComment}>Comment
{this.state.newComment}
)
}
}
要将HTML直接注入React组件,可以使用
注意-根据文档,请谨慎使用此功能,并确保自己不易受到攻击
<div className="newComment" dangerouslySetInnerHTML={{ __html: this.state.newComment }} />