繁体   English   中英

如何键入 React ref 访问数组中的 DOM 元素

[英]How do I type a React ref accessing a DOM element from an array

假设我想访问 JSX 元素数组中的最后一个元素。

let array = [
  <button type="button" />,
  <button type="button" />,
  <button type="button" />,
];

let last = array[array.length - 1];

类型推断在这里工作得很好。

但是现在假设我想将 ref 附加到该数组中的最后一个元素。

let last = React.useRef<HTMLButtonElement>();

let array = [
  <button type="button" />,
  <button type="button" />,
  <button type="button" />,
];

last.current = array[array.length - 1];

上面的代码片段导致了这个错误。

Type 'Element' is missing the following properties from type 'HTMLButtonElement':
disabled, form, formAction, formEnctype, and 249 more.

我想也许我需要显式键入array: HTMLButtonElement[] ,但这只是将错误移至数组声明。

将 ref 类型更改为React.useRef<JSX.Element>将消除错误,但会失去确保其按钮元素的特殊性。

在您的示例中,您可以将 ref 设置为最后一个元素的属性:

let last = React.useRef<Partial<HTMLButtonElement>|null>(null);
let array = [
  <button type="button" />,
  <button type="button" />,
  <button type="button" ref={last} />,
];

但我假设这个例子是简化的,这不适用于你的实际用例......

我的问题示例将 DOM 和 JSX 元素混为一谈。 我在数组中使用了<button> JSX 元素来简化我遇到的问题,但随后错误地创建了一个新问题。

创建 DOM 元素而不是 JSX 元素是可行的。

let last = React.useRef<HTMLButtonElement>();

let array = [
  document.createElement('button'),
  document.createElement('button'),
  document.createElement('button'),
];

last.current = array[array.length - 1];

我们也可以通过在页面上查询得到 DOM 元素的数组(这是我的实际情况)。

let array = document.querySelectorAll<HTMLButtonElement>('button');

暂无
暂无

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

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