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

当前回答

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

其他回答

反应。createRef(类比较)

class ClassApp extends React.Component {
  inputRef = React.createRef<HTMLInputElement>();
  
  render() {
    return <input type="text" ref={this.inputRef} />
  }
}

反应。useRef(钩子/函数比较)

a) Use readonly refs for React-managed DOM nodes:
const FunctionApp = () => {
  // note the passed-in `null` arg ----------------v
  const inputRef = React.useRef<HTMLInputElement>(null)
  return <input type="text" ref={inputRef} />
}

inputRef。通过将Current属性的值初始化为null, Current属性变为只读属性。

b) Use

可变参

for arbitrary stored values akin to instance variables:
const FunctionApp = () => {
  const renderCountRef = useRef(0)
  useEffect(() => {
    renderCountRef.current += 1
  })
  // ... other render code
}

注意:在这种情况下不要初始化useRef为null——它会使renderCountRef类型为只读(参见示例)。如果你需要提供null作为初始值,这样做:

const renderCountRef = useRef<number | null>(null)

回调引用(两个)

// Function component example, class analogue 
const FunctionApp = () => {
  const handleDomNodeChange = (domNode: HTMLInputElement | null) => {
    // ... do something with changed dom node.
  }
  return <input type="text" ref={handleDomNodeChange} />
}

注意:字符串引用被认为是遗留的,在此回答的范围内被省略。

操场上的样品

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

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

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

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

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

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

对于typescript用户,不需要构造函数。

...

private divRef: HTMLDivElement | null = null

getDivRef = (ref: HTMLDivElement | null): void => {
    this.divRef = ref
}

render() {
    return <div ref={this.getDivRef} />
}

...

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

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

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

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