动态调整文本输入框的宽度以适合reactjs

问题描述

我有一个接受文本的文本输入框,我想根据输入宽度动态调整宽度。根据我尝试过的方法,我可以使它足够容易地进行更改,但是该框不能很好地“拥抱”文本,并且右侧仍然存在空白。


<Input
  paddingHorizontal='8px'
  value={value}
  onChange={onChange}
  maxWidth='300px'
  minWidth='120px'
  width={value ? `${width}px` : 120px}

/>

我尝试过的onChange处理程序来设置未产生预期效果的宽度:

  1. 这似乎是最接近的,并且在文本扩展时效果很好,非常适合。

    enter image description here

    但是,删除时效果不佳,并且在侧面留有多余的空白

    enter image description here

const onChange = event => {
    let currentWidth;
    //if text is being deleted
    if(value && (value.length > event.target.value.length)){
      currentWidth = event.target.scrollWidth - 5;

    } else {
      currentWidth = event.target.scrollWidth + 1;
    }
    setValue(event.target.value);      
    setWidth(currentWidth);  

}
  1. 此版本在打字时在侧面留有太多空间

    enter image description here

const onChange = event => {
    //I've tried various numbers here besides 9
    let currentWidth = event.target.value.length * 9;
    setValue(event.target.value);      
    setWidth(currentWidth);  
}

如果您对如何使输入框更好地适合文本有任何想法或建议,请告诉我。 谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)