В компоненте React я хочу сохранить ссылку на дочерний узел, который может различаться по типу (div, img et c.). Поэтому я определил переменную-член:
export class MyComp extends Component<IProperties, IState> {
private triggerRef = React.createRef<HTMLElement>();
...
}
и хочу использовать ее для хранения требуемого ref:
const trigger = <div ref={this.triggerRef} className={className} style={style} />;
Хотя это приводит к ошибке:
Type 'RefObject<HTMLElement>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLDivElement>'.
Property 'align' is missing in type 'HTMLElement' but required in type 'HTMLDivElement'.ts(2322)
lib.dom.d.ts(6708, 5): 'align' is declared here.
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
Строка Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLDivElement>'
говорит, что два типа объектов ref несовместимы, хотя HTMLDivElement
расширяет HTMLElement
. Я ожидаю, что типы ссылок совместимы по присваиванию, так как они явно перекрываются.
Какой правильный подход здесь, без изменения переменной-члена для использования HTMLDivElement
?