我正在使用Typescript处理React。 "重定向"似乎不适合我。 我不知道问题所在。
import * as React from "react"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import store from "./ToDoStore"
import { Redirect} from "react-router-dom";
export class AddTodo extends React.Component {
refs: {
name: (HTMLInputElement);
description: (HTMLInputElement);
}
addTodo() {
store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
alert("Task added successfully");
<Redirect to="/home" push/>
}
render() {
return (
<div id="addtodo">
<TextField
label='Add Todo' ref="name"
/>
<br />
<TextField
label='Add Description' ref="description"
/>
<br />
<PrimaryButton text="Add" onClick={this.addTodo.bind(this)} />
</div>
)
}
}
答案 0 :(得分:2)
这不是打字稿相关的问题。这是<Redirect/>
的不当使用。您正在尝试在回调中使用JSX组件;这不行。您需要做的是在添加待办事项时进行一些状态更改,并在该状态为真时有条件地呈现<Redirect/>
组件。
尝试以下重构。
export class AddTodo extends React.Component {
constructor(props) {
super(props);
this.state = {
shouldRedirect: false
};
this.addTodo = this.addTodo.bind(this);
}
refs: {
name: (HTMLInputElement);
description: (HTMLInputElement);
}
addTodo() {
store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
alert("Task added successfully");
this.setState({ shouldRedirect: true });
}
render() {
return (
<div id="addtodo">
{
this.state.shouldRedirect ?
<Redirect to="/home" push/> :
<div>
<TextField
label='Add Todo' ref="name"
/>
<br />
<TextField
label='Add Description' ref="description"
/>
<br />
<PrimaryButton text="Add" onClick={this.addTodo} />
</div>
}
</div>
);
}
}
答案 1 :(得分:0)
您可以使用this.props.history.push
以编程方式导航到其他页面。
使用react-router-dom withRouter(AddTodo)
导出您的类以使历史记录像
//Import
import { withRouter } from "react-router-dom";
您的组件将
/*Your component*/
class AddTodo extends React.Component {
..your code goes here
}
export default withRouter(AddTodo);
并在您的addTodo
方法
addTodo() {
// Task added successfully
if(success) { // Go to home page if success
this.props.history.push('/home');
}
}