前提概要
draftjs的编辑器和input的区别就是,draft的值与状态是通过editorstate管理的,对比文档参考这里,editorstate的API 参考这里
正文
本章节主要是文本的简单样式控制,分别通过快捷键和按钮来实现
1. RichUtils and Key Commands(快捷键)
RichUtils has information about the core key commands available to web editors, such as Cmd+B (bold), Cmd+I (italic), and so on.
RichUtils 包含了快捷键映射的功能
继续修改components/MyEditor.js
import React from 'react';
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) {
const newState = RichUtils.handleKeyCommand(this.state.editorState, command);
if (newState) {
this.onChange(newState);
return 'handled';
}
return 'not-handled';
}
render() {
const {editorState} = this.state;
return (
<Editor
editorState={editorState}
handleKeyCommand={
this.handleKeyCommand}
onChange={
this.onChange} />
);
}
}
MyEditor.propTypes = {
};
export default MyEditor;
可以在浏览器查看效果,输入一些文字,选中文字使用ctrl+b,和ctrl+i查看效果。
为何返回值是handled和not-handled?更多文档查看如下:
handleKeyCommand
The command argument supplied to handleKeyCommand is a string value, the name of the command to be executed. This is mapped from a DOM key event. See Advanced Topics - Key Binding for more on this, as well as details on why the function returns handled or not-handled.
2. Styling Controls in UI (通过按钮控制样式)
Here’s a super-basic example with a “Bold” button to toggle the BOLD style.
一个通过按钮来实现加粗的例子:
添加如下代码:
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>
<Editor
editorState={
this.state.editorState}
handleKeyCommand={
this.handleKeyCommand}
onChange={
this.onChange}
/>
</div>