如何在draftjs中获取整个contentState?
例如,我想通过单击按钮来修改内容字体大小。默认值为all contentState。用户无需在mac中单击CMD + A.
请原谅我可怜的英语。谢谢你。
答案 0 :(得分:2)
点击cmd+A
后,您可以对整个内容进行选择。单击按钮后,您可以使用draft.js SelectionState
以编程方式执行此操作。看看这个工作示例 - https://jsfiddle.net/k7wghwuj/1/
一些解释。在您应该指定要应用的样式之前。例如,创建两个样式:第一个 - 红色背景,第二个 - 大字体(26px)。定义customStyleMap对象。此对象的键应该是自定义样式和值的唯一名称 - 具有适当样式的对象。
const customStyleMap = {
redBackground: {
backgroundColor: 'red'
},
largeText: {
fontSize: 26
},
};
将此对象传递给Editor组件的customStyleMap
属性:
<Editor
placeholder="Type away :)"
editorState={this.state.editorState}
onChange={this._handleChange}
customStyleMap={customStyleMap}
/>
添加onClick
处理函数。将适当样式的名称作为第一个参数传递。
<button onClick={() => this.applyStyleOnWholeContent('redBackground')}>
set red background for whole content
</button>
<button onClick={() => this.applyStyleOnWholeContent('largeText')}>
set large font size for whole content
</button>
在applyStyleOnWholeContent
内,您应该获得第一个和最后一个ContentBlock
,并使用new SelectionState
构造函数以编程方式设置选择。
applyStyleOnWholeContent = (styleName) => {
const editorState = this.state.editorState;
let currentContent = this.state.editorState.getCurrentContent();
const firstBlock = currentContent.getBlockMap().first();
const lastBlock = currentContent.getBlockMap().last();
const firstBlockKey = firstBlock.getKey();
const lastBlockKey = lastBlock.getKey();
const lengthOfLastBlock = lastBlock.getLength();
let newSelection = new SelectionState({
anchorKey: firstBlockKey,
anchorOffset: 0,
focusKey: lastBlockKey,
focusOffset: lengthOfLastBlock
});
...
之后,使用Modifier.applyInlineStyle
您应该生成新内容
内容状态,更新EditorState
,重置选择并应用更改。
...
currentContent = Modifier.applyInlineStyle(
currentContent,
newSelection,
styleName,
)
let newEditorState = EditorState.push(
editorState,
currentContent,
)
newSelection = new SelectionState({
anchorKey: 0,
anchorOffset: 0,
focusKey: 0,
focusOffset: 0
});
newEditorState = EditorState.forceSelection(newEditorState, newSelection);
this._handleChange(newEditorState);
}