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

如何在Next.js+ShadCN UI项目中替换输入框为Tiptap富文本编辑器?

在Next.js + ShadCN项目中替换表单输入框为Tiptap富文本编辑器

1. 封装可复用的Tiptap编辑器组件

先创建一个独立的编辑器组件,处理内容同步和基础配置,方便在表单中直接使用:

// components/RichTextEditor.tsx
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Link from '@tiptap/extension-link'
import Placeholder from '@tiptap/extension-placeholder'
import { useEffect } from 'react'

interface RichTextEditorProps {
  value: string
  onChange: (content: string) => void
  placeholder?: string
}

export default function RichTextEditor({ value, onChange, placeholder = '请输入内容' }: RichTextEditorProps) {
  const editor = useEditor({
    extensions: [
      StarterKit,
      Link.configure({ openOnClick: true }),
      Placeholder.configure({ placeholder })
    ],
    content: value,
    onUpdate: ({ editor }) => onChange(editor.getHTML()),
    editorProps: {
      attributes: {
        class: 'min-h-[150px] border rounded-md p-3 focus:ring-2 focus:ring-primary/50 outline-none'
      }
    }
  })

  // 同步外部传入的value变化
  useEffect(() => {
    if (editor && editor.getHTML() !== value) {
      editor.commands.setContent(value)
    }
  }, [editor, value])

  return <EditorContent editor={editor} />
}

2. 替换原表单中的Input组件

修改你现有的FormField代码,把原生Input替换为上面封装的编辑器组件,同时保持React Hook Form的字段绑定:

<FormField
  control={form.control}
  name="description"
  render={({ field }) => (
    <FormItem className="mt-6 flex lg:space-x-12 max-lg:space-y-6 lg:flex-row flex-col sm:max-w-5xl max-w-xl justify-between">
      <div className="w-[284px] mt-3">
        <FormLabel className="font-semibold">Description</FormLabel>
      </div>
      <div className="space-y-6 flex-1">
        <FormControl>
          {/* 替换原Input为自定义编辑器 */}
          <RichTextEditor
            value={field.value}
            onChange={field.onChange}
            placeholder="Description"
          />
        </FormControl>
        <FormMessage />
      </div>
    </FormItem>
  )}
/>

额外提示

  • 编辑器样式可以根据ShadCN的设计规范调整class属性,确保和其他表单组件视觉统一
  • 若需要更多富文本功能,可在extensions数组中添加Tiptap的其他扩展(如代码块、表格等)
  • 表单提交时,description字段会存储编辑器输出的HTML内容,若需要纯文本,可将editor.getHTML()替换为editor.getText()

内容的提问来源于stack exchange,提问作者byun Amina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:40:01