如何使用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
相关产品推荐
相关产品推荐

