如何在 React 和 Typescript 中使用 refs [英] How to use refs in React with Typescript

查看:28
本文介绍了如何在 React 和 Typescript 中使用 refs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 中使用 Typescript.我无法理解如何使用 refs 以获得关于 refs 引用的反应节点的静态类型和智能感知.我的代码如下.

import * as React from 'react';接口应用状态{计数:数量;}界面 AppProps {步骤:数量;}接口 AppRefs {步骤输入:HTMLInputElement;}导出默认类 TestApp 扩展 React.Component{构造函数(道具:AppProps){超级(道具);this.state = {计数:0};}增量计数器(){this.setState({count: this.state.count + 1});}使成为() {返回 (<div><h1>你好世界</h1><input type="text" ref="stepInput"/><button onClick={() =>this.incrementCounter()}>Increment</button>计数:{this.state.count}

);}}

解决方案

如果您使用的是 React 16.3+,建议的方式创建引用是使用 React.createRef().

class TestApp extends React.Component{私有 stepInput: React.RefObject;构造函数(道具){超级(道具);this.stepInput = React.createRef();}使成为() {返回 <input type="text" ref={this.stepInput}/>;}}

当组件挂载时,ref 属性的current 属性将被分配给引用的组件/DOM 元素,并在以下情况下分配回null它卸载.因此,例如,您可以使用 this.stepInput.current 访问它.

有关 RefObject 的更多信息,请参阅 @apieceofbart 的回答PR createRef() 已添加.

<小时>

如果您使用的是较早版本的 React (<16.3) 或需要更细粒度地控制何时设置和取消设置 refs,您可以使用 回调引用".

class TestApp extends React.Component{私人 stepInput: HTMLInputElement;构造函数(道具){超级(道具);this.stepInput = null;this.setStepInputRef = element =>{this.stepInput = 元素;};}使成为() {return <input type="text" ref={this.setStepInputRef}/>}}

当组件挂载时,React 将使用 DOM 元素调用 ref 回调,并在卸载时使用 null 调用它.因此,例如,您只需使用 this.stepInput 即可访问它.

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

<小时>

曾经是ref 属性是一个字符串的 API(参见 Akshar Patel 的回答),但由于一些 问题,强烈建议不要使用字符串引用,最终将被删除.

<小时>

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

I'm using Typescript with React. I'm having trouble understanding how to use refs so as to get static typing and intellisense with respect to the react nodes referenced by the refs. My code is as follows.

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

解决方案

If you’re using React 16.3+, the suggested way to create refs is using 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} />;
    }
}

When the component mounts, the ref attribute’s current property will be assigned to the referenced component/DOM element and assigned back to null when it unmounts. So, for example, you can access it using this.stepInput.current.

For more on RefObject, see @apieceofbart's answer or the PR createRef() was added in.


If you’re using an earlier version of React (<16.3) or need more fine-grained control over when refs are set and unset, you can use "callback refs".

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

When the component mounts, React will call the ref callback with the DOM element, and will call it with null when it unmounts. So, for example, you can access it simply using this.stepInput.

By defining the ref callback as a bound method on the class as opposed to an inline function (as in a previous version of this answer), you can avoid the callback getting called twice during updates.


There used to be an API where the ref attribute was a string (see Akshar Patel's answer), but due to some issues, string refs are strongly discouraged and will eventually be removed.


Edited May 22, 2018 to add the new way of doing refs in React 16.3. Thanks @apieceofbart for pointing out that there was a new way.

这篇关于如何在 React 和 Typescript 中使用 refs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆