React: how to make an input only as wide as the amount of text provided?(Reaction:如何使输入的范围与提供的文本量一样宽?)
问题描述
问题很简单: 我正在尝试创建与提供给他们的文本一样大的输入。
沙盒:https://codesandbox.io/s/long-snowflake-6u13n?file=/src/Test.jsx
我的设计意图是动态生成输入,然后允许用户具有特定于每个输入的样式,从而在视觉上帮助根据外部事件拆分每个句子。但在我可以继续前行之前,我的输入容器必须和其中的文本一样大。
为什么不使用文本区?--我有特定于要为其创建唯一样式的每个句子的数据。
有什么想法吗?
推荐答案
这里是一种来自普通Html/css的方法和一个工作代码片段,它将span
中键入的值隐藏在absolute
position
中input
集合的后面。Css可以使span
和input
匹配相同的长度/宽度。拉伸/折叠父对象(label
)将完成作业。
在@silvenon的帮助下,您还可以在代码片段下面找到一个反应样本
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">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;
});
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;
}
<label><span id="tpl"></span><input id='test' value="Some test to try" ></label>
在@silvenon的帮助下,您可以找到该代码的反应示例。
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>
)
}
这篇关于Reaction:如何使输入的范围与提供的文本量一样宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Reaction:如何使输入的范围与提供的文本量一样宽?


- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01