我们知道js并不是脚本语言,在js中存两大问题,一是动态类型检查,容易造成类型bug,二是面向对象支持不完整;
这两大缺陷在ts中得到了解决,ts为JavaScript提供了大量的数据类型,并且完善了面向对象编程。
今天我们来了解一下在react中使用ts:
使用react官方脚手架搭建ts开发环境
create-react-app 项目名称 --template typescript
1.创建类组件
App组件
import React, { Component } from 'react';
import Child from './Child';
interface IProps{}
interface IState{//属性接口(约束state中出现的属性和属性值的类型)
count:number;
}
//
export default class App extends Component<IProps, IState> {
state = {
count:0
}
render() {
let {count} = this.state;
return (
<div>
<h3>App组件</h3>
<p>count:{count}</p>
<button onClick={this.haddleClick}>+1</button>
<hr/>
<Child msg="10001"/>
</div>
)
}
//haddleClick无需在父类中用,也无需子类继承
//所以用private 成员访问修饰符 私有的来定义
private haddleClick = ()=>{//私有方法
let {count}=this.state;
this.setState({count:count+1});
}
}
Child组件
import React, { Component } from 'react'
interface Props{
msg:string;
}
interface State{
name:string
}
export default class Child extends Component<Props, State> {
state = {
name:'tom'
}
render() {
let {msg}=this.props;
let {name}=this.state;
return (
<div>
<h3>Child组件</h3>
<p>父组件通过this.props传递过来的数据msg:{msg}</p>
<p>name:{name}</p>
<button onClick={this.changeName}>Change Name</button>
</div>
)
}
private changeName=()=>{
this.setState({name:"jarry"});
}
}
效果:
点击+1按钮 count值+1 点击Change Name按钮,tom变为jarry
其实和之前在react中使用js是差不多的
只是增加了很多数据类型来约束变量,这样开发的时候代码量会稍微大一些,但是不容易出现类型bug,并且更方便后期维护
2.创建静态组件
Hello组件:
import * as React from 'react';
interface IHelloProps {
message?:string;//带?是可选类型(父类可传可不传)
}
//FC是FunctionComponent的别名
const Hello: React.FC<IHelloProps> = (props) => {
return (
<div>
<h3>Hello组件</h3>
<p>父组件传递的message:{props.message}</p>
</div>
) ;
};
export default Hello;
//父类FC中定义的属性接口
Hello.defaultProps={//设置当前组件props的默认值
message:"嘻嘻嘻"
}
App组件:
import React, { Component } from 'react';
import Hello from './Hello';//静态组件
interface IProps{}
interface IState{
count:number;
}
export default class App extends Component<IProps, IState> {
state = {
count:0
}
render() {
let {count} = this.state;
return (
<div>
<h3>App组件</h3>
<p>count:{count}</p>
<button onClick={this.haddleClick}>+1</button>
<hr/>
{/* 不传值(Hello的props设置的是可选参数,并且组件设置了默认值) */}
<Hello />
{/* 传值 */}
<Hello message="哈哈哈哈" />
</div>
)
}
//haddleClick无需在父类中用,也无需子类继承
//所以用private 成员访问修饰符 私有的来定义
private haddleClick = ()=>{//私有方法
let {count}=this.state;
this.setState({count:count+1});
}
}
效果展示: