React:如何使输入的宽度与提供的文本量一样宽?

kev*_*vin 6 css reactjs styled-components

足够简单的问题: 我正在尝试创建与提供给它们的文本一样大的输入。

沙箱:https://codesandbox.io/s/long-snowflake-6u13n? file=/src/Test.jsx

我的设计意图是动态生成输入,然后允许用户具有特定于每个输入的样式,这些样式在视觉上有助于根据外部事件分解每个句子。但在我继续前进之前,输入容器的大小必须与其中的文本一样大,这一点非常重要。

为什么不使用文本区域?-- 我有每个句子特有的数据,我想为其创建独特的样式。

有什么想法吗?

G-C*_*Cyr 5

这是一种来自纯 HTML/CSS 和工作片段的方法,spaninputabsolute position. CSS 可以使spaninput匹配相同的长度/宽度。拉伸/折叠父级 ( label) 将完成该工作。

感谢@silvenon,您还可以在代码片段下方找到一个反应示例

var val = document.querySelector('#test');
let tpl = document.querySelector('#tpl');
let text = val.value;
 tpl.textContent= text;

val.addEventListener("input", function () {// onchange ...
  let text= val.value;
  //console.log(text);
  tpl.textContent= text;
  });
Run Code Online (Sandbox Code Playgroud)
label {
  display: inline-block;
  position: relative;
  min-width: 2em;
  min-height: 1.4em;
}

#tpl {
  white-space: pre;
  /* max-width : could be wised to set a maximum width and overflow:hidden; */
}

#test {
  font-family: inherit;
  font-size: inherit;
  position: absolute;
  vertical-align: top;
  top: 0;
  left: 0;
  width: 100%;
  background: white;
}
Run Code Online (Sandbox Code Playgroud)
<label><span id="tpl"></span><input id='test' value="Some test to try" ></label>
Run Code Online (Sandbox Code Playgroud)

感谢 @silvenon,您可能会找到该代码的 React 示例。

const SentenceInput = styled.input`
  padding: 0;
  margin: 0;
  border: none;
  border: 1px solid black;
  /* added styles */
  font-family: inherit;
  font-size: inherit;
  position: absolute;
  vertical-align: top;
  top: 0;
  left: 0;
  width: 100%;
  background: white;
`

const Label = styled.label`
  display: inline-block;
  position: relative;
  min-width: 2em;
  min-height: 1.4em;
`

const Template = styled.span`
  white-space: pre;
  /* max-width : could be wised to set a maximum width and overflow:hidden; */
`

const Sentence = ({ initialValue }) => {
  const [value, setValue] = React.useState(initialValue)
  return (
    <Label>
      <Template>{value}</Template>
      <SentenceInput
        type="text"
        value={value}
        onChange={(event) => {
          setValue(event.target.value)
        }}
      />
    </Label>
  )
}
Run Code Online (Sandbox Code Playgroud)