我正在使用带有React的Typescript。我很难理解如何使用refs来获得关于refs引用的react节点的静态类型和智能感知。我的代码如下
导入*作为“React”的React;
接口应用状态{
计数:数字;
}
接口AppProps{
步骤:编号;
}
接口装置{
stepInput:HTMLInputElement;
}
导出默认类TestApp扩展React.Component<;AppProps、AppState>;{
构造函数(props:AppProps){
超级(道具);
此.state={
计数:0
};
}
递增计数器(){
this.setState({count:this.state.count+1});
}
render(){
返回(
<;div>;
<;h1>;你好世界<;/h1>;
<;输入类型=“text”ref=“stepInput”/>;
<;button onClick={()=>;this.incrementCounter()}>;Increment<;/button>;
计数:{this.state.Count}
<;/div>;
);
}}
如果您使用的是React 16.3+,建议使用React.createRef()创建引用
类TestApp扩展了React.Component<;AppProps、AppState>;{
私有步骤输入:React.reObject<;HTMLInputElement>;;
建造师(道具){
超级(道具);
this.stepInput=React.createRef();
}
render(){
return<;input type=“text”ref={this.stepInput}/>;;
}
}
组件装载时,ref属性的current属性将分配给引用的组件/DOM元素,并在卸载时分配回null。例如,您可以使用this.stepInput.current访问它
有关reObject的更多信息,请参阅@apieceofbart的答案或添加了PRcreateRef()
如果您使用的是早期版本的React(<;16.3),或者需要更细粒度地控制何时设置和取消设置引用,则可以使用“回调引用”
类TestApp扩展了React.Component<;AppProps、AppState>;{
私有stepInput:HTMLInputElement;
建造师(道具){
超级(道具);
this.stepInput=null;
this.setStepInputRef=元素=>{
this.step输入=元素;
};
}
render(){
return<;input type=“text”ref={this.setStepInputRef}/>;
}
}
当组件装载时,React将使用DOM元素调用ref回调,并在卸载时使用null调用它。例如,您可以使用this.stepInput访问它
通过将ref回调定义为类上的绑定方法,而不是内联函数(如本答案的前一版本),可以避免在更新期间调用两次回调
过去有一个API,其中ref属性是一个字符串(参见Akshar Patel的回答),但是由于一些问题,字符串ref被强烈劝阻,最终将被删除
于2018年5月22日编辑,在React 16.3中添加了新的参考方法。感谢@apieceofart指出有一种新方法。