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>

结束

相关推荐
JarvanMo14 分钟前
在 Flutter 中正确处理文本缩放
前端
深蓝电商API16 分钟前
HTML 解析入门:用 BeautifulSoup 轻松提取网页数据
前端·爬虫·python·beautifulsoup
excel35 分钟前
JavaScript 运算符与 Vue 中的 1 << n 应用
前端
上单带刀不带妹1 小时前
Vue3 全局 API 转移详解
前端·javascript·vue.js·vue3·api
怕冷的火焰(~杰)1 小时前
yarn安装electron和better-sqlite3失败问题(rebuild:better-sqlite3)
前端·javascript·electron
IT_陈寒1 小时前
JavaScript性能优化:7个90%开发者不知道的V8引擎黑科技
前端·人工智能·后端
摸鱼的春哥1 小时前
“全栈模式”必然导致“质量雪崩”!和个人水平关系不大
前端·javascript·后端
Eme丶2 小时前
Nginx部署vue以及转发配置记录
前端·vue.js·nginx
大气层煮月亮2 小时前
Oracle EBS ERP之报表开发—嵌入Web中的报表预览、报表打印
前端·数据库·oracle
excel2 小时前
Vue 中 v-show 与 v-if 的全面解析
前端