gpt4 book ai didi

reactjs - TypeScript react : RouteComponentProps types error or cant access history

转载 作者:行者123 更新时间:2023-12-03 13:28:43 25 4
gpt4 key购买 nike

我制作了一个组件并像...一样使用它

<TopNav
loggedIn={global.shared.loggedIn} // false
fullName={global.shared.fullName} // ''
avatar={global.shared.avatarId} // ''
/>

在 TopNav 组件内部,我希望能够访问我传入的 props 和 props.history 或其他无需刷新即可以编程方式导航用户的方式。

import React from 'react';
import { RouteComponentProps } from 'react-router-dom';


interface PropsInterfaceNew {
avatar: string;
loggedIn: boolean;
fullName: string;
}

interface PropsInterface
extends RouteComponentProps<PropsInterfaceNew> {}
// ^ Error

const TopNav: React.FC<PropsInterface> = (props: PropsInterface) => {
...
const firstName = props.fullName.split(' ')[0]; // I need props.fullName & others
const search = (event: React.FormEvent) => {
event.preventDefault();
props.history.push('/my/profile'); // I need props.history
};

错误是

Type 'PropsInterfaceNew' does not satisfy the constraint '{ avatar?: string | undefined; loggedIn?: string | undefined; fullName?: string | undefined; }'.
Types of property 'loggedIn' are incompatible.
Type 'boolean' is not assignable to type 'string | undefined'.ts(2344)

或者,如果我完全删除历史记录,如下所示,我没有错误,但无法访问历史记录

interface PropsInterface {
avatar: string;
loggedIn: boolean;
fullName: string;
}

const TopNav: React.FC<PropsInterface> = (props: PropsInterface) => {
...

@hardik 如果我将 export { TopNav }; 替换为...

  export withRouter(TopNav);
//^ err1 ^err2

我收到新错误 2

statements are not aligned (align)tslint(1)

和错误1

Declaration or statement expected.ts(1128)

最佳答案

如果要传递RouteComponentProps,则必须用withRouter包装组件,然后导出。

export withRouter(TopNav);

Prop 类型应该是这样的,

interface PropsInterface extends RouteComponentProps {
avatar: string;
loggedIn: boolean;
fullName: string;
}

const TopNav: React.FC<PropsInterface> = (props: PropsInterface) => {....

这肯定会解决您的问题!

关于reactjs - TypeScript react : RouteComponentProps types error or cant access history,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com