Javascript 财产';查询选择器';不存在于类型';节点';。打字
我有以下代码: test.htmlJavascript 财产';查询选择器';不存在于类型';节点';。打字,javascript,typescript,Javascript,Typescript,我有以下代码: test.html <!DOCTYPE html> <html> <head lang="zh-CN"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title></title> </head> <body>
<!DOCTYPE html>
<html>
<head lang="zh-CN">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title></title>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
<script src="test.js"></script>
</body>
</html>
我发现了错误
Error:(2, 28) TS2339: Property 'querySelector' does not exist on type 'Node'.
我在书中发现了下面的句子
parentNode是当前节点的父节点。元素的父节点是元素节点、文档节点或DocumentFragment节点。
这是我的测验
var ul = document.querySelector('ul')
undefined
ul.parentNode.toString()
[object HTMLDivElement]"
谁能告诉我有什么问题吗
typescript的版本是1.4
谁能告诉我有什么问题吗
TypeScript的API视图。目前无法说foo.parentNode
的类型取决于foo
的类型。目前推断它总是属于节点
类型,并且节点
不包含API查询选择器
(可在元素
上获得)
修理
使用类型断言,如图所示:
var box = document.querySelector('#box');
console.log((<Element>box.parentNode).querySelector('#box'));
var-box=document.querySelector(“#box”);
console.log((box.parentNode).querySelector('#box');
使用
let-box=document.querySelector(“#box”);
对于那些正在寻找使用Typescript和JSX的解决方案的人:
const box = document.querySelector('#box');
console.log((box.parentNode as HTMLElement).querySelector('#box'));
parentNode成员返回父节点,可以是Element或node类型。必须使用parentElement来遍历DOM树,而不是使用parentNode来遍历XML树
var box = document.querySelector('#box');
console.log(box.parentElement.querySelector('#box'));
我正在使用
createreact应用程序2.1
的TS设置
对我来说,这是一个将dom
添加到tsconfig.json
中的lib
列表的问题
"lib": [..., "dom"]
对于任何在React Hooks/tsx中遇到此问题的人,我将我的useRef声明更新为HTMLElement | null
,然后我可以使用可选链接而不会出错
const formRef = useRef(null as HTMLElement | null);
const form = formRef?.current?.querySelector('form');
"lib": [..., "dom"]
const formRef = useRef(null as HTMLElement | null);
const form = formRef?.current?.querySelector('form');