gpt4 book ai didi

javascript - 单击按钮不会使用 draft.js 添加内联样式

转载 作者:行者123 更新时间:2023-11-30 07:12:33 25 4
gpt4 key购买 nike

我正在尝试将使用 draft.js 的富文本编辑器添加到 React 项目中。我已经能够按照他们的文档添加它并处理键盘命令。我还添加了两个按钮来做粗体和斜体,但问题是当我点击按钮时,编辑器状态不会改变并且没有添加内联样式但是如果我选择文本并点击按钮样式是添加到该文本。我不明白我哪里做错了。

import React, { Component } from 'react';
import {Editor, EditorState, RichUtils} from 'draft-js';
import './App.css';

class App extends 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';
}

_onBoldClick() {
this.onChange(RichUtils.toggleInlineStyle(
this.state.editorState, 'BOLD'));
}

_onItalicClick() {
this.onChange(RichUtils.toggleInlineStyle(
this.state.editorState, 'ITALIC'));
}

render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Text formatting using Draft.js</h1>
</header>
<div className="toolbar">
<button className="btn" onClick={this._onBoldClick.bind(this)}>B</button>
<button className="btn" onClick={this._onItalicClick.bind(this)}>I</button>
</div>
<div className="notePage">
<Editor
editorState={this.state.editorState}
handleKeyCommand={this.handleKeyCommand}
onChange={this.onChange}
isCollapsed="true"
/>
</div>
</div>
);
}
}

最佳答案

发生这种情况是因为默认情况下 onClick 会导致 Editor 失去焦点。要解决此问题,请执行以下操作:

  _onBoldClick (e) {
e.preventDefault()
this.onChange(RichUtils.toggleInlineStyle(
this.state.editorState, 'BOLD'))
}

_onItalicClick (e) {
e.preventDefault()
this.onChange(RichUtils.toggleInlineStyle(
this.state.editorState, 'ITALIC'))
}

并将 onClick 更改为 onMouseDown:

<button className='btn' onMouseDown={this._onBoldClick.bind(this)}>B</button>

<button className='btn' onMouseDown={this._onItalicClick.bind(this)}>I</button>

附加说明

始终在顶部包含 Draft.css:

import 'draft-js/dist/Draft.css'

来自 the documentation :

This CSS should be included when rendering the editor, as these styles set defaults for text alignment, spacing, and other important features. Without it, you may encounter issues with block positioning, alignment, and cursor behavior.

关于javascript - 单击按钮不会使用 draft.js 添加内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com