javascript - 在 React 中自动缩放输入到值的宽度
问题描述
我想要一个宽度适应其内容的输入。
我正在尝试对类似问题实施此答案,但使用 React:
import React, { useState } from 'react';
export default () => {
const [content, setContent] = useState('');
const [width, setWidth] = useState(0);
const changeHandler = evt => {
setContent(evt.target.value);
};
return (
<wrapper>
<span id="hide">{content}</span>
<input type="text" autoFocus style={{ width }} onChange={changeHandler} />
</wrapper>
);
};
问题是我不知道如何查询跨度的宽度,以便更改输入的宽度(使用setWidth
)。
我怎样才能做到这一点?
解决方案
嗯,这很有趣!我尝试了一些不同的想法,但没有一个是完美的——尤其是如果它们是用一些可敬的代码编写的。
然而,我发现了这篇文章并决定尝试一下。 https://stackoverflow.com/a/43488899/3293843
我确信它存在缺陷,例如,除非我使用等宽字体,否则它确实很有趣。但也许有一些 css 技巧可以解决这个问题?
// Normally I'd go for ES6 imports, but to make it run as a StackOverflow snippet I had to do it this way
const { useState, useRef } = React;
const GrowingInput = () => {
const [width, setWidth] = useState(0);
const changeHandler = evt => {
setWidth(evt.target.value.length);
};
return (
<input style={{ width: width +'ch'}} type="text" autoFocus onChange={changeHandler} />
)
};
const App = () => {
return (
<p>Lorem ipsum {<GrowingInput />} egestas arcu.</p>
);
};
// Render it
ReactDOM.render(<App />, document.getElementById("react"));
input {
font-family: Courier;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
您是否考虑过使用 acontenteditable
代替?
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content
推荐阅读
- c# - 无法更改 Xamarin Forms v4.1 中的工具栏图标
- java - 如何制作这个菜单
- java - 从线程调用 repaint()
- c# - C# AES-GCM 分成几部分
- java - 非常令人困惑的 Java.lang.RuntimeException: java.io.FileNotFoundException:
- android - Android Q (10) 请求访问所有存储的权限。范围存储
- docker - xwiki (docker) 在 Synology 上安装 500 – 内部服务器错误
- google-apps-script - 成功运行后谷歌表格自定义功能错误“未知功能”
- javascript - 如何在 Windows 中正确杀死由 node.js/electron 生成的 child_process?
- html - 将一个 UL 居中,将另一个放在右侧