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

如何在带有Typescript的React中使用refs,第1张

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

如果您使用的是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指出有一种新方法。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5614946.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存