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

如何在React中实现文本与HTML模式切换的输入表单

React 实现纯文本/HTML 切换输入表单

实现思路

  • 状态驱动模式切换:用useState维护当前编辑模式(text/html)和输入内容两个核心状态,确保模式切换时内容同步不丢失。
  • 条件渲染输入组件:根据当前模式,分别渲染纯文本<textarea>或HTML输入+预览组合,适配不同编辑场景。
  • 共享内容状态:两种模式共用同一个内容状态变量,切换模式时无需额外做内容转换。
  • 安全提醒:HTML模式下使用dangerouslySetInnerHTML渲染预览时,务必注意XSS风险,生产环境建议添加内容过滤逻辑。

完整示例代码

import { useState } from 'react';

export default function ToggleableInputForm() {
  // 控制当前编辑模式:'text' 为纯文本,'html' 为HTML模式
  const [editMode, setEditMode] = useState('text');
  // 存储输入的内容,两种模式共用
  const [inputContent, setInputContent] = useState('');

  // 切换编辑模式
  const switchMode = () => {
    setEditMode(prev => prev === 'text' ? 'html' : 'text');
  };

  // 处理纯文本输入变化
  const handleTextInput = (e) => {
    setInputContent(e.target.value);
  };

  // 处理HTML代码输入变化
  const handleHtmlInput = (e) => {
    setInputContent(e.target.value);
  };

  return (
    <div style={{ maxWidth: '600px', margin: '2rem auto', padding: '0 1rem' }}>
      {/* 模式切换按钮 */}
      <div style={{ marginBottom: '16px' }}>
        <button
          onClick={switchMode}
          style={{ padding: '8px 16px', cursor: 'pointer', border: 'none', borderRadius: '4px', backgroundColor: '#007bff', color: 'white' }}
        >
          切换到{editMode === 'text' ? 'HTML' : '纯文本'}模式
        </button>
      </div>

      {/* 纯文本模式输入框 */}
      {editMode === 'text' && (
        <textarea
          value={inputContent}
          onChange={handleTextInput}
          rows={10}
          style={{ width: '100%', padding: '8px', border: '1px solid #ced4da', borderRadius: '4px', fontSize: '14px' }}
          placeholder="在此输入纯文本内容..."
        />
      )}

      {/* HTML模式输入+预览 */}
      {editMode === 'html' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <textarea
            value={inputContent}
            onChange={handleHtmlInput}
            rows={6}
            style={{ width: '100%', padding: '8px', border: '1px solid #ced4da', borderRadius: '4px', fontSize: '14px' }}
            placeholder="在此输入HTML代码,例如 <h1>标题</h1>..."
          />
          <div style={{ padding: '16px', border: '1px solid #ced4da', borderRadius: '4px' }}>
            <h5 style={{ margin: '0 0 8px 0' }}>HTML预览</h5>
            <div
              dangerouslySetInnerHTML={{ __html: inputContent }}
              style={{ minHeight: '100px', fontSize: '14px' }}
            />
          </div>
        </div>
      )}

      {/* 提交按钮 */}
      <div style={{ marginTop: '16px' }}>
        <button
          style={{ padding: '8px 16px', cursor: 'pointer', border: 'none', borderRadius: '4px', backgroundColor: '#28a745', color: 'white' }}
          onClick={() => {
            // 这里可以替换为实际的提交逻辑
            console.log('提交的内容:', inputContent);
            alert('提交成功,内容已打印到控制台');
          }}
        >
          提交表单
        </button>
      </div>
    </div>
  );
}

关键说明

  • 纯文本模式下,输入的内容会被原样保存,不会解析任何HTML标签。
  • HTML模式提供了代码输入框和实时预览区域,方便用户编写和查看HTML效果。
  • 提交时直接使用inputContent状态即可,无需额外转换,两种模式的内容都能直接获取。
  • 重要安全提示:如果你的应用允许用户提交HTML内容,一定要在后端或前端添加XSS过滤(比如使用DOMPurify库),防止恶意脚本注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:41:24