# TypeScript与react结合一些注意点(持续更新)
# DOM元素的选择
const body: HTMLElement = document.body;
if (document.documentElement) {
const scrollTop = document.documentElement.scrollTop || body.scrollTop;
}
1
2
3
4
2
3
4
# scroll滚动事件的绑定
constructor(props: any) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
}
public componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
public componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# withRouter
当你想要访问match
、location
、history
这三个对象的时候可以使用withRouter
来包裹组件来实现高阶组件(HOC)
结合TypeScript
想访问match
、location
、history
时,需要引入RouteComponentProps
。
以withRouter出发看React高阶组件 (opens new window)
import { RouteComponentProps, withRouter } from 'react-router-dom';
interface IArticleProps extends RouteComponentProps<any> {
...
}
class ArticleItem extends React.Component<IArticleProps> {
public componentWillMount() {
const id = this.props.match.params.id;
...
}
public render() {
...
}
}
export default withRouter<IArticleProps>(ArticleItem);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 路由
利用
props
中children
属性来实现路由link
跳转利用
Loadable
来实现按需加载路由
// router.tsx
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import * as Loadable from 'react-loadable';
const LoadComponent = (view: string): any => {
return () => import(`./pages/${view}`);
};
const RouterList: IRouteMap[] = [
{
path: '/',
component: LoadComponent('Home')
},
...
]
const RouterMap = () => (
<Router basename="/rtblog">
<Layout>
<Switch>
{RouterList.map((item, i) => (
<Route
key={i}
exact={true}
path={item.path}
component={Loadable({
loader: item.component,
loading: Loading
})}
/>
))}
</Switch>
</Layout>
</Router>
)
export default RouterMap;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// layout.tsx
...
public render() {
const { children } = this.props;
return (
<div className="layout-wrapper">
<Header />
<MainContent children={children} />
<BackTop>
<div className="back-top-inner">UP</div>
</BackTop>
</div>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
← React状态管理 React Hooks →