当前位置: 首页 > 工具软件 > Draft.js > 使用案例 >

(翻译)draft.js 创建简单的富文本编辑器

充阳秋
2023-12-01

https://facebook.github.io/draft-js/docs/quickstart-rich-styling.html#content

上一节创建了双向绑定的draft.js 的编辑器基础,这一节将创建一个简单的富文本编辑器。(通过键盘快捷键和按钮两种方式,实现最简单的加粗功能)

主要用到了RichUtils 的toggleInlineStyle和handleKeyCommand两个方法

import React from 'react';
import ReactDOM from 'react-dom';
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})

            console.log(this.state);
        };

        // 监听键盘事件
        this.handleKeyCommand = this.handleKeyCommand.bind(this);

    }

    _onBoldClick() {
        //RichUtils.toggleInlineStyle 将现有state  ,转换为新的state,
        // toggle 如果已经加粗了则取消加粗,如果没有则加粗
        let newState = RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD');
        this.onChange(newState);
    }

    handleKeyCommand(command) {
        const newState = RichUtils.handleKeyCommand(this.state.editorState, command);

        if (newState) {
            this.onChange(newState);
            return 'handled';
        }
        return 'not-handled';
    }

    render() {
        return (
            <div>
                <button onClick={this._onBoldClick.bind(this)}>Bold</button>
                <Editor handleKeyCommand={this.handleKeyCommand} editorState={this.state.editorState}
                        onChange={this.onChange}/>
            </div>
        );
    }
}

ReactDOM.render(
    <MyEditor />,
    document.getElementById('container')
);
 类似资料: