用Typescript编写的ReactJS组件
示例
实际上,您可以像在Facebook的示例中那样在Typescript中使用ReactJS的组件。只需将“jsx”文件的扩展名替换为“tsx”:
//helloMessage.tsx:
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);但是为了充分利用Typescript的主要功能(静态类型检查),应该做几件事:
1)将React.createClass示例转换为ES6类:
//helloMessage.tsx:
class HelloMessage extendsReact.Component{
render() {
return <div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(<HelloMessage name="John" />, mountNode);2)接下来添加Props和State接口:
interface IHelloMessageProps {
name:string;
}
interface IHelloMessageState {
//在我们的情况下是空的
}
class HelloMessage extends React.Component<IHelloMessageProps, IHelloMessageState> {
constructor(){
super();
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);如果程序员忘记传递道具,现在Typescript将显示错误。或者,如果他们添加了接口中未定义的道具。
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短