我使用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文档中推荐的那样使用回调样式(https://facebook.github.io/react/docs/refs-and-the-dom.html),你可以在类中添加一个属性定义:

export class Foo extends React.Component<{}, {}> {
// You don't need to use 'references' as the name
references: {
    // If you are using other components be more specific than HTMLInputElement
    myRef: HTMLInputElement;
} = {
    myRef: null
}
...
 myFunction() {
    // Use like this
    this.references.myRef.focus();
}
...
render() {
    return(<input ref={(i: any) => { this.references.myRef = i; }}/>)
}

其他回答

一种方法(我一直在做的)是手动设置:

refs: {
    [string: string]: any;
    stepInput:any;
}

然后你甚至可以用一个更好的getter函数来包装它(例如这里):

stepInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.stepInput);

只是添加一个不同的方法-你可以简单地强制转换你的引用,像这样:

let myInputElement: Element = this.refs["myInput"] as Element

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

从React 16.3开始,添加refs的方法就是使用React。正如Jeff Bowen在回答中指出的那样,createRef。然而,你可以利用Typescript来更好地输入你的引用。

在你的例子中,你在input元素上使用了ref。所以我的做法是

class SomeComponent extends React.Component<IProps, IState> {
    private inputRef: React.RefObject<HTMLInputElement>;
    constructor() {
        ...
        this.inputRef = React.createRef();
    }

    ...

    render() {
        <input type="text" ref={this.inputRef} />;
    }
}

通过这样做,当你想使用那个ref时,你可以访问所有的输入法:

someMethod() {
    this.inputRef.current.focus(); // 'current' is input node, autocompletion, yay!
}

你也可以在自定义组件上使用它:

private componentRef: React.RefObject<React.Component<IProps>>;

然后,例如,获得道具:

this.componentRef.current.props; // 'props' satisfy IProps interface

编辑:这不再是在Typescript中使用refs的正确方式。看看杰夫·鲍恩的回答,给它点赞,以提高它的曝光度。

找到了问题的答案。在类中使用如下引用。

refs: {
    [key: string]: (Element);
    stepInput: (HTMLInputElement);
}

谢谢@basarat指出了正确的方向。