我使用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和TypeScript时获取用户输入。部分基于其他评论和此链接https://medium.com/@basarat/strong -typed-refs-for-react-typescript-9a07419f807#.cdrghertm
/// <reference path="typings/react/react-global.d.ts" />
// Init our code using jquery on document ready
$(function () {
ReactDOM.render(<ServerTime />, document.getElementById("reactTest"));
});
interface IServerTimeProps {
}
interface IServerTimeState {
time: string;
}
interface IServerTimeInputs {
userFormat?: HTMLInputElement;
}
class ServerTime extends React.Component<IServerTimeProps, IServerTimeState> {
inputs: IServerTimeInputs = {};
constructor() {
super();
this.state = { time: "unknown" }
}
render() {
return (
<div>
<div>Server time: { this.state.time }</div>
<input type="text" ref={ a => this.inputs.userFormat = a } defaultValue="s" ></input>
<button onClick={ this._buttonClick.bind(this) }>GetTime</button>
</div>
);
}
// Update state with value from server
_buttonClick(): void {
alert(`Format:${this.inputs.userFormat.value}`);
// This part requires a listening web server to work, but alert shows the user input
jQuery.ajax({
method: "POST",
data: { format: this.inputs.userFormat.value },
url: "/Home/ServerTime",
success: (result) => {
this.setState({ time : result });
}
});
}
}
来自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+,建议使用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属性的当前属性将被赋值给被引用的组件/DOM元素,并在卸载时赋值回null。例如,你可以使用this。stepput。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将使用DOM元素调用ref回调,并在卸载时使用null调用它。例如,你可以简单地使用this.stepInput访问它。
通过将ref回调定义为类上的绑定方法,而不是内联函数(与此答案的前一个版本一样),可以避免在更新期间调用回调两次。
曾经有一个API,其中ref属性是一个字符串(参见Akshar Patel的答案),但由于一些问题,字符串引用是强烈反对的,最终将被删除。
编辑于2018年5月22日,在React 16.3中添加了新的裁判方式。感谢@apieceofbart指出了一种新方法。