contentEditable 实现可编辑区域

背景

最近看豆包的时候,发现他的代码写AI编程模块 如下

借助的是contentEditable 来实现的,操作比较友好,可以随意输入可编辑数据,有类似于 placeholder等属性

如果我们开发大模型,免不了东西借鉴一下,下面基于react 来封装 一个 使用contentEditable 来实现的可编辑区域组件

实现重点

  1. 开启 contentEditable 后 如何模拟 placeholder
  2. 如何判断何时展示 placeholder 何时展示真实内容
  3. 调整优化以及受控组件封装

代码如下

js 复制代码
import React, { useState, useRef, useEffect } from 'react'

interface ContentEditablePromptProps {
  placeholder?: string
  className?: string
  value?: string
  onChange?: (value: string) => void
}

const ContentEditablePrompt: React.FC<ContentEditablePromptProps> = ({
  placeholder = '请输入',
  className = '',
  value = '',
  onChange
}) => {
  const contentEditableRef = useRef<HTMLDivElement>(null)
  const [isEmpty, setIsEmpty] = useState(true)
  const [internalValue, setInternalValue] = useState(value)

  // 更新内容并处理空状态
  const updateContent = (newValue: string) => {
    if (!contentEditableRef.current) return

    // 更新内部状态
    setInternalValue(newValue)

    // 调用父组件的onChange回调
    if (onChange) {
      onChange(newValue)
    }

    // 更新空状态
    const isNowEmpty = newValue.trim() === ''
    setIsEmpty(isNowEmpty)

    // 处理空状态下的placeholder显示
    if (contentEditableRef.current) {
      if (isNowEmpty && contentEditableRef.current.innerHTML === '<br>') {
        contentEditableRef.current.innerHTML = ''
      }
    }
  }

  // 处理输入事件
  const handleInput = () => {
    if (!contentEditableRef.current) return
    updateContent(contentEditableRef.current.textContent || '')
  }

  // 处理失去焦点事件
  const handleBlur = () => {
    if (!contentEditableRef.current) return

    // 规范化内容
    const newValue = contentEditableRef.current.textContent || ''
    updateContent(newValue)

    // 确保DOM内容与内部状态一致
    if (contentEditableRef.current.textContent !== internalValue) {
      contentEditableRef.current.textContent = internalValue
    }
  }

  // 初始化内容和响应外部value变化
  useEffect(() => {
    if (!contentEditableRef.current) return

    // 只有当外部value与内部值不同时才更新
    if (value !== internalValue) {
      setInternalValue(value)
      contentEditableRef.current.textContent = value
      setIsEmpty(value.trim() === '')
    }
  }, [value])

  return (
    <div
      ref={contentEditableRef}
      className={`p-2 px-3 w-fit rounded-2xl flex items-center ${
        isEmpty
          ? 'after:content-[attr(data-placeholder)] after:tracking-[1px] bg-[#EEF6FF] font-bold text-[#007DFA] word-spacing-2'
          : 'bg-[#EEF6FF] font-bold text-[#007DFA] word-spacing-2'
      } ${className}`}
      contentEditable
      data-placeholder={placeholder}
      onInput={handleInput}
      onBlur={handleBlur}
      suppressContentEditableWarning
    />
  )
}

export default ContentEditablePrompt

使用如下:

js 复制代码
<EditableArea placeholder='预设提取项' value='' onChange={onChangeValue}></EditableArea>

结束

相关推荐
胡萝卜术8 小时前
当大模型遇上浏览器:用 React + WebGPU 在前端跑通 DeepSeek-R1 的实战笔记
前端·javascript·面试
不好听6138 小时前
Tailwind CSS 原子化 CSS 完全入门:为什么现代前端开发都在用?
前端·css
触底反弹8 小时前
🔥 React 零基础入门(上):环境搭建 + JSX 深度解析
前端·react.js·typescript
why技术9 小时前
分享一套我一直在使用的 AICoding 组合拳,小而美的典范。
前端·后端·ai编程
朦胧之9 小时前
AI应用-消费流式输出
前端·javascript·ai编程
小林ixn9 小时前
在浏览器跑通 15 亿参数大模型:我用 React + WebGPU 复刻了 DeepSeek-R1
前端·react.js·前端框架
Csvn10 小时前
容器查询 @container 实战:告别无休止的媒体查询
前端
稚南城才子,乌衣巷风流12 小时前
函数:编程中的核心概念
开发语言·前端·javascript
IT_陈寒13 小时前
为什么我的JavaScript异步代码总是不按顺序执行?
前端·人工智能·后端
索西引擎13 小时前
【React】useState 状态更新机制:批量更新策略与“异步“错觉的深层解析
前端·react.js·前端框架