我使用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。FC,添加HTMLDivElement接口:

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

然后像下面这样使用它:

return <div ref={myRef} />;

其他回答

从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

首先添加一个导入

import React, { useRef } from "react";

那么这个

const studentCapacityRef = useRef<HTMLInputElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLAreaElement>(null);

或者这个

const studentCapacityRef = useRef<HTMLDivElement>(null);

等等……

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

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)}
    />
}

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

如果你使用的是React 16.3+,建议使用React. createref()创建引用。

class TestApp extends React.Component<AppProps, AppState> {
    private stepInput: React.RefObject<HTMLInputElement>;
    constructor(props) {
        super(props);
        this.stepInput = React.createRef();
    }
    render() {
        return <input type="text" ref={this.stepInput} />;
    }
}

当组件挂载时,ref属性的当前属性将被赋值给被引用的组件/DOM元素,并在卸载时赋值回null。例如,你可以使用this。stepput。current访问它。

有关RefObject的更多信息,请参见@apieceofbart的回答或PR createRef()。


如果你正在使用React的早期版本(<16.3),或者需要更细粒度地控制何时设置和取消设置引用,你可以使用“回调引用”。

class TestApp extends React.Component<AppProps, AppState> {
    private stepInput: HTMLInputElement;
    constructor(props) {
        super(props);
        this.stepInput = null;
        this.setStepInputRef = element => {
            this.stepInput = element;
        };
    }
    render() {
        return <input type="text" ref={this.setStepInputRef} />
    }
}

当组件挂载时,React将使用DOM元素调用ref回调,并在卸载时使用null调用它。例如,你可以简单地使用this.stepInput访问它。

通过将ref回调定义为类上的绑定方法,而不是内联函数(与此答案的前一个版本一样),可以避免在更新期间调用回调两次。


曾经有一个API,其中ref属性是一个字符串(参见Akshar Patel的答案),但由于一些问题,字符串引用是强烈反对的,最终将被删除。


编辑于2018年5月22日,在React 16.3中添加了新的裁判方式。感谢@apieceofbart指出了一种新方法。