【问题标题】:Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element' error in React无法在“窗口”上执行“getComputedStyle”:参数 1 不是 React 中的“元素”类型错误
【发布时间】:2021-12-30 10:07:49
【问题描述】:

我正在尝试在 React 应用程序中使用 JavaScript 自动扩展(向上)文本框。得到这个错误。也尝试使用 window.getElementbyId 代替,但这不起作用。

[![error image][1]][1]
   <ReactTextareaAutocomplete
   id="textbox"
   className="message-input"
   placeholder="Type your message.."/>
const tx = document.getElementsByTagName("ReactTextareaAutocomplete");
const maxheight = 100;
const normalheight = window.getComputedStyle(tx[0]).getPropertyValue('height').replace("px", "");
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute("style", "margin-top:-3px;" + "height:" + (tx[i].scrollHeight > maxheight ? maxheight : tx[i].scrollHeight) + "px;overflow-y:hidden;");
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.marginTop = (normalheight - this.style.height.replace("px", "")) + "px";
  this.style.height = "auto";
  this.style.height = (this.scrollHeight > maxheight ? maxheight : this.scrollHeight) + "px";
}


  


  [1]: <https://i.stack.imgur.com/1UbRS.png>

【问题讨论】:

    标签: javascript html reactjs react-native javascript-objects


    【解决方案1】:

    实现useRef() 来访问元素。

    在元素上添加ref 属性。

    <ReactTextareaAutocomplete ref={rtaRef} />
    

    对于函数:

    const tx = useRef(null);
    

    如果您有多个组件实例,请使用循环使用循环索引创建唯一的ref

    【讨论】:

    • 但仍然显示相同的错误
    • 我使用的“ref”代码是“getElementsByTagName”的替代品。编码时,使用标签名称“ReactTextareaAutocomplete”,但在渲染过程中,React 将其视为组件并将其转换为 html,因此不能使用“getElementsByTagName”。
    猜你喜欢
    • 2019-12-11
    • 2022-06-23
    • 2017-12-27
    • 2021-08-24
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2020-12-22
    相关资源
    最近更新 更多