首页 > 解决方案 > 在 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)。

我怎样才能做到这一点?

标签: javascriptreactjsreact-hooksresize

解决方案


嗯,这很有趣!我尝试了一些不同的想法,但没有一个是完美的——尤其是如果它们是用一些可敬的代码编写的。

然而,我发现了这篇文章并决定尝试一下。 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


推荐阅读