###前言 一直想学学TypeScript,尝试尝试带类型的js怎么写,有啥优点。正好这两天有时间结合着react写写小例子。
- 搭建环境 不想折腾webpack来自己配ts+react的环境就用typescript官网推荐的搭建方法来干
create-react-app my-app --scripts-version=react-scripts-ts
直接在终端里运行这个等待项目构建完成就能开干了。 目录结构如下图 具体每个目录干啥的就不一一解释了,看目录名字基本都能知道,因为直接用脚手架生成的所以基本不要我们自己去配置的,直接开始我们的示例就好了 index.tsx是入口文件,渲染了App这个组件,所以我们就直接在App这个里面来进行下一步,目标是实现一个React的render props(和react HOC作用差不多据说比HOC更好用)来实现屏幕显示当前鼠标位置的功能。 - 开始写MousePoint方法 ts写react除了要写一些类型声明外基本套路还是一样了,首先我们引入React
import * as React from 'react'
然后因为我们要实现在屏幕上显示当前位置功能,所以接下来就是写一个能显示鼠标位置的component。
class MousePoint extends React.Component {super(props){this.state = {x:null,y:null}}const move = (e) => {this.setState({x:e.clientX,y:e.clientY})}render(){return (<div style={{height:1000px;}} onMouseMove={this.move}>{this.props.render({x:this.state.x,y:this.state.y})}</div>)}
}
复制代码
代码比较简单唯一需要解释的就是那个调用的render函数了,这个就是我们实现render props的关键,将MousePoint组建的鼠标位置传出去的方法。 但是目前为止我们还是没有用到ts的知识,现在还是在用js在写,怎么用js来写呢只要加上我们的类型声明就perfect了。
interface MousePointProps {render:(point: {x: number|null,y: number|null}) => React.ReactElement<HTMLDivElement>
}interface MOusePointState {x: number|null;}class MousePoint extends React.Component<MousePointProps, MousePointState> {super(props: MousePointProps){this.state = {x:null,y:null}}const move = (e: React.MouseEvent<HTMLDivElement>) => {this.setState({x:e.clientX,y:e.clientY})}render(){return (<div style={{height:1000px;}} onMouseMove={this.move}>{this.props.render({x:this.state.x,y:this.state.y})}</div>)}
}
复制代码
首先解释下interface是接口的意思,作用就是规定了传入的值必须有接口中定义名称且的类型要一致。具体的解释和用法可以去typescript官网看看解释的肯定比我好。
- 写一个需要用到mouse point 位置的组件,也就是相当于我们日常开发中的具体业务组件
interface RenderPointsProps {point: {x: number|null;y: number|null;};
}const RenderPoint: React.SFC<RenderPointsProps> = (props) => {const {point} = props;return (<div> current posiont of x is {point.x} y is {point.y} </div>)
}
复制代码
需要注意的一个地方就是这里我们用了React.SFC来作为react function component的类型声明。
- 将所有的东西组合起来就over了
class App extends React.Component {render() {return (<div><MousePoint renders={(points: {x: number|null; y: number|null}) => { return <RenderPoints point={points}/>; }} /></div>);}
}export default App;
复制代码
总结:只是一个小例子,但我自己通过这个例子对typescript有了一定的了解,加深了对render props的理解,也希望这篇文章能给你一点收获。