我使用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>
    );
}}

当前回答

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

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

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

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

其他回答

如果你在使用React。FC,添加HTMLDivElement接口:

const myRef = React.useRef<HTMLDivElement>(null);

然后像下面这样使用它:

return <div ref={myRef} />;

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

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

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

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

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

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

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

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

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

输入:htmlinterment =反应。

来自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版本)