我使用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类型定义
type ReactInstance = Component<any, any> | Element;
....
refs: {
[key: string]: ReactInstance
};
你可以像下面这样访问你的refs元素
stepInput = () => ReactDOM.findDOMNode(this.refs['stepInput']);
没有重新定义refs索引。
正如@manakor提到的,你可能会得到这样的错误
属性“stepInput”在类型“{[key: string]”上不存在:
组件|元素;}
如果你重新定义refs(取决于你使用的IDE和ts版本)
从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