我使用Typescript与React。我有麻烦理解如何使用参考,以获得静态类型和智能感知的反应节点引用的参考。我的代码如下。

import * as React from 'react';

interface AppState {
    count: number;
}

interface AppProps {
    steps: number;
}

interface AppRefs {
    stepInput: HTMLInputElement;
}

export default class TestApp extends React.Component<AppProps, AppState> {

constructor(props: AppProps) {
    super(props);
    this.state = {
        count: 0
    };
}

incrementCounter() {
    this.setState({count: this.state.count + 1});
}

render() {
    return (
        <div>
            <h1>Hello World</h1>
            <input type="text" ref="stepInput" />
            <button onClick={() => this.incrementCounter()}>Increment</button>
            Count : {this.state.count}
        </div>
    );
}}

当前回答

来自React类型定义

    type ReactInstance = Component<any, any> | Element;
....
    refs: {
            [key: string]: ReactInstance
    };

你可以像下面这样访问你的refs元素

stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);

没有重新定义refs索引。

正如@manakor提到的,你可能会得到这样的错误

属性“stepInput”在类型“{[key: string]”上不存在: 组件|元素;}

如果你重新定义refs(取决于你使用的IDE和ts版本)

其他回答

来自React类型定义

    type ReactInstance = Component<any, any> | Element;
....
    refs: {
            [key: string]: ReactInstance
    };

你可以像下面这样访问你的refs元素

stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);

没有重新定义refs索引。

正如@manakor提到的,你可能会得到这样的错误

属性“stepInput”在类型“{[key: string]”上不存在: 组件|元素;}

如果你重新定义refs(取决于你使用的IDE和ts版本)

当你有一个元素数组的时候,你可以这样做:

const textInputRefs = useRef<(HTMLDivElement | null)[]>([])

...

const onClickFocus = (event: React.BaseSyntheticEvent, index: number) => {
    textInputRefs.current[index]?.focus()
};

...

{items.map((item, index) => (
    <textInput
        inputRef={(ref) => textInputs.current[index] = ref}
    />
    <Button
        onClick={event => onClickFocus(event, index)}
    />
}

首先添加一个导入

import React, { useRef } from "react";

那么这个

const studentCapacityRef = useRef<HTMLInputElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLAreaElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLDivElement>(null);

等等……

在这种情况下,我总是这样做 抓住裁判

输入:htmlinterment =反应。

如果你不想转发你的ref,在Props界面你需要使用RefObject<CmpType>类型从import React, {RefObject}从' React ';