【发布时间】:2019-06-02 03:37:02
【问题描述】:
我是 react 新手,我正在学习使用 typescript 进行反应编程导航。由于大多数教程都使用 java 脚本,我无法解决使用 typescript 编程导航的问题
就像我尝试过的大多数教程一样
this.props.history.push("/page");
显示错误'history' does not exist on type
我尝试了几种解决方案,例如
const history=createBrowserHistory();
history.push("/page")
此方法将更改 url 路径,但组件不会像这里提到的那样加载 https://github.com/ReactTraining/react-router/issues/4059
我也尝试了另一种解决方案
this.context.push("/page");
这给了我以下错误 TypeError: _this.context.push 不是函数
我的完整代码
import * as queryString from 'query-string';
import * as React from 'react';
interface IrentalProps{
name:string,
}
class Rental extends React.Component<IrentalProps, any> {
public extracturl=()=>{
const stringfy=queryString.parse(location.search);
return stringfy.id;
}
public handleClick=()=>{
this.context.push("/page"); //issue
}
public render() {
return (
<div style={{paddingTop:100}}>
{this.extracturl()}
<button onClick={this.handleClick}>navigate</button> //calling the function
</div>
);
}
}
export default Rental;
我只需要像在 SPA 中使用 typescript 和 browserrouter 一样点击按钮导航到另一个页面
注意:redirect 可以正常工作,并且带有 createhashhistory() 的 hashrouter 也可以正常工作。
【问题讨论】:
标签: reactjs typescript react-router react-tsx