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

如何使用React useState创建受控SVG文本输入框?

在SVG中实现由React useState单独控制的可编辑文本框

原始实现及问题

通过外层<div contentEditable>让SVG内文本可编辑的方式存在诸多不符合需求的问题,原始代码如下:

<div contentEditable>
  <svg viewBox='0 0 300 300'>
    <text x=2 y=40>
      Can this be a text input field?
    </text>
    <text y=80>
      But not this
    </text>
    <text y=110>
      And not this
    </text>
  </svg>
</div>

具体问题:

  • 核心需求基于React,希望可编辑文本由useState状态控制
  • 当前SVG内所有文本均可编辑,实际仅需第一个文本区域具备可编辑能力
  • 存在光标大幅右移等BUG

可行解决方案

利用SVG的<foreignObject>标签嵌入HTML输入组件,结合React状态实现单独控制,测试效果良好:

import { useState } from 'react';
import { FormControl } from 'react-bootstrap';

function SvgEditableText() {
  const [test, setTest] = useState('here is some text');

  return (
    <svg>
      <foreignObject x="40" y="40" width="300" height="150">
        <div xmlns="http://www.w3.org/1999/xhtml">
          <FormControl
            className='modal-input'
            type='text'
            value={test}
            onChange={(e) => setTest(e.target.value)}
            name='firstname'
            placeholder='First Name'
          />
        </div>
      </foreignObject>
      {/* 其他SVG元素 */}
    </svg>
  );
}

注:FormControl来自react-bootstrap,也可根据需求替换为原生<input>或其他UI库的输入组件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:10:34