使用 Typescript 在 React 中重定向

Yog*_*Yog 5 redirect typescript reactjs react-router

我正在使用 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>
    )
}
Run Code Online (Sandbox Code Playgroud)

}

Kyl*_*son 3

这不是与打字稿相关的问题。这是使用不当<Redirect/>。您正在尝试在回调中使用 JSX 组件;这是行不通的。您需要做的是在添加待办事项时更改一些状态,并<Redirect/>在该状态为 true 时有条件地渲染组件。

尝试下面的重构。

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)