[英]I am getting this error on angular:src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'
[英]Why am I getting error TS2339 on querySelectorAll for checkbox property 'checked' does not exist
我正在開發一個於 2016 年創建的 reactJS 應用程序,我正在嘗試為其修補功能。 文件以 .tsx 擴展名,應用程序編譯器在渲染之前查找所有打字稿錯誤。 所以現在我試圖在單擊主復選框輸入時實現選擇所有復選框,但就目前而言,當我調用“checkboxElement.checked = true”時,我收到了 TS2339 錯誤。
主復選框
<input type="checkbox" onChange={this.checkAllBoxes} />
從屬復選框
<Col lg={1}>
<input type="checkbox" />
</Col>
選擇所有框方法
checkAllBoxes() {
const allCheckBoxes = document.querySelectorAll("input[type='checkbox']") as NodeListOf<Element>;
allCheckBoxes.forEach(checkBox => {
console.log(checkBox);
if(checkBox && checkBox.checked) checkBox.checked = true;
});
}
正如我在 console.log 中看到的, checkBox
已經checked getter and setter method
但是我在編譯時遇到了 TS2339 錯誤。 我很難相信我正面臨這樣一個基本功能的問題。
錯誤:(我在編譯窗口中記錄了兩次此錯誤)
error TS2339: Property 'checked' does not exist on type 'Element'.
我嘗試將查詢從 querySelectorAll 更改為 getElementByID 和 getElementsByClassname 並進行相應更改。 我更喜歡 querySelectorAll 但沒有嚴格的指導方針。 我看過這個github 鏈接,他們說他們已經解決了這個問題,但它對我不起作用。
Typescript 無法知道返回的 HTML 元素是輸入(它們確實具有checked
屬性。
最簡單的解決方案是斷言querySelectorAll
返回一個HTMLInputElement
列表
const allCheckBoxes = document.querySelectorAll("input[type='checkbox']") as NodeListOf<HTMLInputElement>;
allCheckBoxes.forEach(checkBox => {
console.log(checkBox);
if(checkBox && checkBox.checked) checkBox.checked = true;
});
您正在將 allCheckBoxes 列表轉換為 NodeListOf,但 Element(正確地)沒有檢查屬性。
相反,您應該將其轉換為 NodeListOf,它是復選框的正確接口(checked 屬性僅針對元素定義)
像 for 循環一樣迭代而不轉換為NodeListOf<Element>
。
checkAllBoxes() {
const allCheckBoxes = document.querySelectorAll("input[type='checkbox']");
if(allCheckBoxes){
for(let i = 0; i< allCheckBoxes.length ; i++){
console.log(allCheckBoxes[i]);
if(allCheckBoxes[i] && allCheckBoxes[i].checked) {
allCheckBoxes[i].checked = true;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.