现在,我们已经建立了顶级API的基础,我们可以进一步研究如何将基本的富文本样式添加到Draft编辑器中。
本文还提供了一个富文本示例。
EditorState: 由你操控
前一篇文章介绍了EditorState对象,它是编辑器完整状态的快照,由编辑器核心通过onChange属性提供支持。
但是,由于您的顶级React组件负责维护状态,所以您还可以自由地以任何您认为合适的方式将changes应用到EditorState对象。
例如,对于内联和块样式的行为,RichUtils模块提供了许多有用的函数来帮助处理状态。
类似地,Modifier模块还提供了许多通用操作,允许您应用编辑,包括对文本、样式等的更改。此模块是一组编辑函数,它们组成更简单、更小的编辑函数来返回所需的EditorState对象。
对于本例,我们将使用RichUtils模块来演示如何在顶级组件中应用基本的富样式。
RichUtils and Key Commands
RichUtils有关于web编辑可用的核心快捷键命令,如Cmd+B(粗体)、Cmd+I(斜体)等。
我们可以通过handleKeyCommand prop属性观察和处理键盘key命令,并将它们与RichUtils模块中相对应的函数相关联,以应用或删除所需的样式。
import {Editor, EditorState, RichUtils} from 'draft-js';class MyEditor extends React.Component {constructor(props) {super(props);this.state = {editorState: EditorState.createEmpty()};this.onChange = editorState => this.setState({editorState});this.handleKeyCommand = this.handleKeyCommand.bind(this);}handleKeyCommand(command, editorState) {const newState = RichUtils.handleKeyCommand(editorState, command);if (newState) {this.onChange(newState);return 'handled';}return 'not-handled';}render() {return (<EditoreditorState={this.state.editorState}handleKeyCommand={this.handleKeyCommand}onChange={this.onChange}/>);}}
**handleKeyCommand**提供给>handleKeyCommand的>command参数是一个字符串值,即要执行的命令的名称。这个是从DOM的键盘事件映射过来的。>editorState参数代表了当前最新的editor编辑器的state。因为在处理键盘事件时,Draft可能会在内部更改它并返回新的state。在handleKeyCommand中使用编辑器状态的这个实例。请参阅> 高级主题-键绑定以获得更多信息,以及关于函数返回>handled或>not-handled的详细信息。
Styling Controls in UI
在React组件中,可以添加按钮或其他控件,以允许用户在编辑器中修改样式。在上面的例子中,我们使用已知的键盘命令,但是我们可以添加更复杂的UI来控制和实现这些丰富的特性。
这里有一个超级基础的例子,用一个BOLD按钮来控制BOLD样式。
class MyEditor extends React.Component {// ..._onBoldClick() {this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD'));}render() {return (<div><button onClick={this._onBoldClick.bind(this)}>Bold</button><EditoreditorState={this.state.editorState}handleKeyCommand={this.handleKeyCommand}onChange={this.onChange}/></div>);}}
