小编典典

如何在带有Typescript的React中使用refs

reactjs

我在React中使用Typescript。我在理解如何使用refs方面遇到麻烦,以便相对于refs引用的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>
    );
}}

阅读 491

收藏
2020-07-22

共1个答案

小编典典

如果您使用的是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属性的current属性将分配给引用的组件/
DOM元素,并null在卸载时分配回该属性。因此,例如,您可以使用进行访问this.stepInput.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将ref使用DOM元素调用回调,并null在卸载时使用DOM元素调用回调。因此,例如,您可以使用轻松访问它this.stepInput

通过将ref回调定义为类的绑定方法,而不是内联函数),可以避免更新过程中两次调用该回调。


曾经是一个API,其中ref属性是一个字符串(见AKSHAR特尔的答案,但由于一些
问题,串裁判的强烈反对,并最终将被删除。


编辑于2018年5月22日,以在React 16.3中添加执行引用的新方法。 感谢@apieceofbart指出有一种新方法。

2020-07-22