如何在React中使用Typescript进行路由更改?

huangapple go评论73阅读模式
英文:

How do I make a route change in React using Typescript?

问题

我正在遵循ZTM课程编码,制作一个人脸识别应用程序,但我正在使用TypeScript而不是JavaScript来构建我的应用程序,避免使用any类型。我对这门语言还不够了解,所以请指导我如何解决以下问题。

问题很简单。我希望当单击相应的按钮时,登出页面会出现。然而,我无法像在JavaScript中那样使这个任务成为可能。

让我展示一下我的代码是什么样子,以使问题更容易理解。首先,这是我的主要App组件,包括其接口和与问题相关的部分:

interface IAppState {
  input: string,
  imageUrl: string,
  box: Object,
  route: string
}

class App extends Component<{title: string}, IAppState> {
  constructor(props: {title: string}) {
    super(props);
    this.state = {
      input: '',
      imageUrl: '',
      box: {},
      route: 'signin'
    }
  }

这是主要App组件的一部分,它使状态发生变化并将我们路由到主页,包括render()方法,您可以在其中看到我的属性onRouteChange

onRouteChange = ({route}) => {
    this.setState({route: route});
  }

  render() {
    return (
      <div className="App">
        <ParticlesBg type="cobweb" bg={true} />
        <Navigation onRouteChange={this.onRouteChange} />
        { this.state.route === 'signin'
          ? <SignIn onRouteChange={this.onRouteChange}/>
          : <>
              <Logo />
              <Rank />
              <ImageLinkForm title='image link form'
              onInputChange={this.onInputChange}
              onButtonSubmit={this.onButtonSubmit}
              />
              <FaceRecognition imageUrl={this.state.imageUrl}/>
            </>
        }
      </div>
    );
  }

在我的Navigation组件中,有登出按钮,它应该将我们路由回登录页面

interface INavigationProps {
    onRouteChange: MouseEventHandler<HTMLInputElement>;
}

const Navigation: FC<INavigationProps> = ({ onRouteChange }) => {
    return (
        <nav style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <p onClick={() => onRouteChange('signin')} className='f3 link dim black underline pa3 pointer'>Sign Out</p>
        </nav>
    );
}

使用给定的代码,登出按钮不起作用。出现错误。

我明显看到的第一个错误与route元素有关:绑定元素'route'隐含具有'any'类型

第二个错误我不明白如何修复:

类型'({ route }: { route: any; }) => void'不能分配给类型'MouseEventHandler<HTMLInputElement>'
  参数'__0''event'的类型不兼容。
    类型'MouseEvent<HTMLInputElement, MouseEvent>'中缺少属性'route',但在类型'{ route: any; }'中是必需的。

最后一个错误在我的Navigation组件中:类型'string'的参数无法分配给类型'MouseEvent<HTMLInputElement, MouseEvent>'

我尝试使用接口和类型来解决这个问题,但我找不到解决方案。如何使登出按钮将我们路由回登录页面

英文:

I am coding along the ZTM course, making a face recognition app, but instead of Javascript, I am using Typescript to build my app, avoiding using any type. I am new to the language and don't fully grasp its nuances, so please advise me on how to resolve the issue below.

The problem is simple. I want the Sign Out page to appear when we click the corresponding button. However, I can't make this task possible like it's made in Javascript.

Let me show you what my code looks like to make it simpler to understand the problem. Firstly, there is my main App component, including its interface and parts that are important to the issue:

interface IAppState {
  input: string,
  imageUrl: string,
  box: Object,
  route: string
}

class App extends Component&lt;{title: string}, IAppState&gt; {
  constructor(props: {title: string}) {
    super(props);
    this.state = {
      input: &#39;&#39;,
      imageUrl: &#39;&#39;,
      box: {},
      route: &#39;signin&#39;
    }
  }

Here is the part of the main App component that makes the state change and routes us to the main page, including the render() method, where you can see my property onRouteChange:

onRouteChange = ({route}) =&gt; {
    this.setState({route: route});
  }

  render() {
    return (
      &lt;div className=&quot;App&quot;&gt;
        &lt;ParticlesBg type=&quot;cobweb&quot; bg={true} /&gt;
        &lt;Navigation onRouteChange={this.onRouteChange} /&gt;
        { this.state.route === &#39;signin&#39;
          ? &lt;SignIn onRouteChange={this.onRouteChange}/&gt;
          : &lt;&gt;
              &lt;Logo /&gt;
              &lt;Rank /&gt;
              &lt;ImageLinkForm title=&#39;image link form&#39;
              onInputChange={this.onInputChange}
              onButtonSubmit={this.onButtonSubmit}
              /&gt;
              &lt;FaceRecognition imageUrl={this.state.imageUrl}/&gt;
            &lt;/&gt;
        }
      &lt;/div&gt;
    );
  }

In my Navigation component, there is the Sign Out button, which should route us back to the Sign In page:

interface INavigationProps {
    onRouteChange: MouseEventHandler&lt;HTMLInputElement&gt;;
}

const Navigation: FC&lt;INavigationProps&gt; = ({ onRouteChange }) =&gt; {
    return (
        &lt;nav style={{ display: &#39;flex&#39;, justifyContent: &#39;flex-end&#39; }}&gt;
            &lt;p onClick={() =&gt; onRouteChange(&#39;signin&#39;)} className=&#39;f3 link dim black underline pa3 pointer&#39;&gt;Sign Out&lt;/p&gt;
        &lt;/nav&gt;
    );
}

With a given code the Sign Out button doesn't work. Errors appear.

The first one that's obvious to me is regarding the route element: Binding element &#39;route&#39; implicitly has an &#39;any&#39; type.

And the second one that I don't understand how to fix:

Type &#39;({ route }: { route: any; }) =&gt; void&#39; is not assignable to type &#39;MouseEventHandler&lt;HTMLInputElement&gt;&#39;.
  Types of parameters &#39;__0&#39; and &#39;event&#39; are incompatible.
    Property &#39;route&#39; is missing in type &#39;MouseEvent&lt;HTMLInputElement, MouseEvent&gt;&#39; but required in type &#39;{ route: any; }&#39;.

The last error is in my Navigation component: Argument of type &#39;string&#39; is not assignable to parameter of type &#39;MouseEvent&lt;HTMLInputElement, MouseEvent&gt;&#39;.

I was playing with interfaces and types to resolve this, but I couldn't find the solution. How do I make the Sign Out button route us back to the Sign In page?

答案1

得分: 0

以下是翻译好的部分:

我已经进行了更多的研究,以下是最终无错误的代码。首先,修复了interface IAppState中的一行:

route: MouseEventHandler | undefined | string

然后将onRouteChange更改为以下内容,指定其类型:

onRouteChange = (route: MouseEventHandler | undefined | string) => {
return this.setState({route: route});
}

然后最终的更改是针对Navigation组件

interface INavigationProps {
onRouteChange: (route: MouseEventHandler | undefined | string) => void;
}

const Navigation: FC = ({ onRouteChange }) => {
return (
<nav style={{ display: 'flex', justifyContent: 'flex-end' }}>
<p onClick={() => onRouteChange('signin')} className='f3 link dim black underline pa3 pointer'>Sign Out

);
}

这样,我可以从主页访问登录页面,使用退出按钮

英文:

I have done more research and here's the final error-free code below. Firstly, fixed the line in interface IAppState to:

route: MouseEventHandler&lt;HTMLInputElement&gt; | undefined | string

Then redacted onRouteChange to look like this, stating its types accordingly:

onRouteChange = (route: MouseEventHandler&lt;HTMLInputElement&gt; | undefined | string) =&gt; {
    return this.setState({route: route});
  }

And then final changes were made to the Navigation component:

interface INavigationProps {
    onRouteChange: (route: MouseEventHandler&lt;HTMLInputElement&gt; | undefined | string) =&gt; void;
}

const Navigation: FC&lt;INavigationProps&gt; = ({ onRouteChange }) =&gt; {
    return (
        &lt;nav style={{ display: &#39;flex&#39;, justifyContent: &#39;flex-end&#39; }}&gt;
            &lt;p onClick={() =&gt; onRouteChange(&#39;signin&#39;)} className=&#39;f3 link dim black underline pa3 pointer&#39;&gt;Sign Out&lt;/p&gt;
        &lt;/nav&gt;
    );
}

That way I can access Sign In page from the home page, using Sing Out button.

huangapple
  • 本文由 发表于 2023年2月10日 15:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定