reactjs - DraftJs - 使用 Modifier.removeInlineStyle() 用新的内容状态更新编辑器状态
问题描述
我有一个设置字体大小内联样式的功能。它主要工作,除了循环几个字体大小后,我必须切换按钮两次。所以为了解决这个问题,我想循环当前选择的内容状态,删除所有当前字体大小样式,然后切换新样式。这是我到目前为止所拥有的,除了Modifier.removeInlineStyle()
似乎没有被应用,我仍然留下了我原来的问题。
状态设置:
constructor(props: RichTextEditorComponentProps) {
super(props);
this.state = this.propsToState(props);
}
propsToState(props: RichTextEditorComponentProps) {
return {
editorState: props.content ? EditorState.createWithContent(
ContentState.createFromBlockArray(
convertFromHTML(props.content).contentBlocks,
convertFromHTML(props.content).entityMap
)
) : EditorState.createEmpty()
};
}
类中的方法:
onFontSizeStyleClick(fontStyle: string) {
const contentState = this.state.editorState.getCurrentContent();
const styles = this.state.editorState.getCurrentInlineStyle();
const selection = this.state.editorState.getSelection();
Object.keys(FontStyleMap).forEach(style => {
if (styles.has(style)) {
Modifier.removeInlineStyle(contentState, selection, style);
}
});
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, fontStyle));
}
然后从以下位置调用:
<button
type="button"
className="style-button"
onClick={() => this.onFontSizeStyleClick('fontSizeXS')}>
SM
</button>
<button
type="button"
className="style-button"
onClick={() => this.onFontSizeStyleClick('fontSizeNormal')}>
N
</button>
<button
type="button"
className="style-button"
onClick={() => this.onFontSizeStyleClick('fontSizeL')}>
L
</button>
<button
type="button"
className="style-button"
onClick={() => this.onFontSizeStyleClick('fontSizeXL')}>
XL
</button>
解决方案
我需要使用 EditorState.push 作为参数调用我的 onChange 方法:
onFontSizeStyleClick(fontStyle: string) {
let contentState = this.state.editorState.getCurrentContent();
const styles = this.state.editorState.getCurrentInlineStyle();
const selection = this.state.editorState.getSelection();
Object.keys(FontStyleMap).forEach(style => {
if (styles.has(style)) {
contentState = Modifier.removeInlineStyle(contentState, selection, style);
}
});
contentState = Modifier.applyInlineStyle(contentState, selection, fontStyle);
this.onChange(EditorState.push(this.state.editorState, contentState, 'change-inline-style'));
}
推荐阅读
- python - 在python中构建路径
- python - Python 忽略 if/elif 语句
- azure - 比较两个表以在 Azure 数据工厂中动态查找缺失的行
- next.js - 如何使用 Next.js router.push 到 Formik 的动态 api 路由,得到 404(未找到)错误
- microsoft-graph-api - Microsoft Graph API 可以获取 Teams 用户的状态消息吗?
- java - 将项目添加到列表但打印时为空 [JAVA]
- python - 需要重新格式化文本文件,将扬声器文本向上移动到扬声器标签
- python - 如何打破计数
- c# - WPF 中是否有与 imagebox 等效的 picturebox.graphics() winforms?
- javascript - Microsoft Graph 的 createUploadSession、Content-Range Header 错误