简体   繁体   English

React Typescript元素类型

[英]React Typescript element types

What's the type of the following statement in React? React中以下语句的类型是什么?

let element = <div>Blah blah</div>

I thought I could use element: HTMLElement but when I do, I get Property 'accessKey' is missing in type 'Element' . 我以为我可以使用element: HTMLElement但是当我这样做时,我Property 'accessKey' is missing in type 'Element'

What about another imported component? 那另一个进口组件怎么样?

import Row from './partials/Row';
let row = <Row cols={cols} />

The type for the div jsx element is HTMLFactory<HTMLDivElement> . div jsx元素的类型是HTMLFactory<HTMLDivElement>

The reference you have isn't for an actual dom element in the browser but for a react element which represent such an element which might not be rendered yet. 您拥有的引用不是浏览器中的实际dom元素,而是表示可能尚未呈现的元素的react元素。

The html properties should be accessed through the props: 应该通过props访问html属性:

let element = <div>Blah blah</div>
console.log(element.props.accessKey);

If you'd like to get the dom element you can use the ref attribute : 如果你想获得dom元素,你可以使用ref属性

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument 当ref属性用于HTML元素时,ref回调接收底层DOM元素作为其参数

So: 所以:

let divElement: HTMLDivElement;
let element = <div ref={ (el) => { divElement = el; console.log(el); } }>Blah blah</div>

In the case of the imported Row , again, you have a reference to a react element which has a dom representation. 在导入的Row的情况下,您再次引用具有dom表示的react元素。
Which properties or methods it has depends on the class itself. 它具有哪些属性或方法取决于类本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM