You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Draft-JS:如何创建带不可编辑前置文本的自定义<h1>块

在Draft-JS中实现带不可编辑提示的自定义H1块

我之前做过类似的需求,给你分享下最靠谱的实现方式——核心是利用Draft-JS的自定义块渲染器,在渲染H1元素时嵌入不可编辑的提示文本,完全不破坏编辑器的原生逻辑:

1. 先定义自定义块类型

给这个特殊的标题块起个唯一标识,比如'custom-heading-one',后续切换块类型时会用到它:

import { EditorState, Modifier } from 'draft-js';

// 示例:把选中块切换为自定义H1块的工具函数
const toggleCustomHeading = (editorState) => {
  const selection = editorState.getSelection();
  const newContent = Modifier.setBlockType(
    editorState.getCurrentContent(),
    selection,
    'custom-heading-one'
  );
  return EditorState.push(editorState, newContent, 'change-block-type');
};

2. 编写自定义块渲染组件

这是核心部分:在<h1>里添加一个不可编辑的提示元素,用contentEditable={false}锁定它,再通过样式和用户输入内容区分开:

const CustomHeadingBlock = (props) => {
  const { block, contentState } = props;
  const userInput = contentState.getBlockForKey(block.getKey()).getText();

  return (
    <h1 style={{ paddingLeft: '4px' }}>
      {/* 不可编辑的提示文本 */}
      <span 
        contentEditable={false}
        style={{
          color: '#888',
          marginRight: '10px',
          userSelect: 'none', // 防止用户选中提示文本
          fontSize: '0.9em'
        }}
      >
        TITLE
      </span>
      {/* 用户可编辑的标题内容 */}
      {userInput}
    </h1>
  );
};

3. 把渲染器绑定到编辑器

最后给Editor组件配置blockRendererFn,告诉Draft-JS遇到'custom-heading-one'类型的块时,用我们的自定义组件渲染:

import { Editor } from 'draft-js';
import { useState } from 'react';

const MyDraftEditor = () => {
  const [editorState, setEditorState] = useState(() => 
    EditorState.createEmpty()
  );

  // 块渲染匹配函数
  const blockRenderer = (block) => {
    if (block.getType() === 'custom-heading-one') {
      return {
        component: CustomHeadingBlock,
        editable: true, // 确保块的主体内容仍可编辑
      };
    }
    return null; // 其他块用默认渲染逻辑
  };

  return (
    <Editor
      editorState={editorState}
      onChange={setEditorState}
      blockRendererFn={blockRenderer}
    />
  );
};

关键细节说明

  • contentEditable={false}:这是让提示文本不可编辑的核心,Draft-JS会自动跳过这个元素的编辑事件,完全不会影响用户输入。
  • userSelect: 'none':避免用户不小心选中提示文本,让交互更顺畅。
  • 样式区分:用低对比度的灰色和小字号,让提示文本只起引导作用,不抢用户输入的注意力。

这种实现方式完全贴合Draft-JS的设计理念,不会出现编辑器状态异常的问题,用起来很稳定。

内容的提问来源于stack exchange,提问作者Damien Monni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:30:33