首页 > 解决方案 > 在 react typescript 组件上实现 RouteComponentProps 时使用什么类型

问题描述

我正在尝试使用 react-router-dom 制作我的第一个接收参数的组件。这是我的组件:

const ProductDetailsPage: React.FC<IPage & RouteComponentProps<any>> = (props: Props) => {

    useEffect(() => {
        const id = props.match.params.id;
    }
    return <h1>product details</h1>
}

interface Props {
    match: {
        params: {
            id: string | undefined;
        };
    };
}

这里 eslint 向我显示了一个我不应该使用的警告,any但我不明白在这里设置什么类型。
我也写了props: Props,但我不知道这是否是这样做的正确方法。

更新更多预览代码:

export default interface IPage {
    name: string;
}

const routes: IRoute[] = [
    {
        path: '/products/:id',
        name: 'details',
        component: ProductDetailsPage,
        exact: true,
    },
];

const ProductsPage: React.FC<IPage> = () => {
    const match = useRouteMatch();

    return (
        <div>
            <h4>This is products page</h4>
            <div>
                <Link to={`${match.url}/44`}>Product 44</Link>
                <Link to={`${match.url}/45`}>Product 44</Link>
                <Link to={`${match.url}/46`}>Product 44</Link>
            </div>
            <Switch>
                {routes.map((route, index) => {
                    return (
                        <Route
                            key={index}
                            path={route.path}
                            render={(props: RouteComponentProps<any>) => (
                                <route.component name={route.name} {...props} {...route.props} />
                            )}
                        />
                    );
                })}
            </Switch>
        </div>
    );
};

interface Props {
    match: {
        params: {
            id: string | undefined;
        };
    };
}

const ProductDetailsPage: React.FC<IPage & RouteComponentProps<Props>> = (props) => {
    const [message, setMessage] = useState<string>('');

    useEffect(() => {
        const id = props.match.params.id;

        if (id) {
            setMessage(`Show details for product: ${id}`);
        } else {
            setMessage(`No parameter passed`);
        }
    }, [props.match.params.id]);

    return <h4>{message}</h4>;
};

export default withRouter(ProductDetailsPage);

标签: reactjstypescriptreact-routerreact-router-domreact-typescript

解决方案


中的泛型 ( T)RouteComponentProps<T>定义了 params 类型。

参数值始终是 astringundefined

如果参数未知,最好使用Record<string, string | undefined>输入参数。

type Params = { id: string | undefined; };

const Test: React.FC<RouteComponentProps<Params>> = ({
    match: { params: { id } }
}) => {
    const idIsStringOrUndefined: string | undefined = id;

    return null;
}

道具也应该通过使用React.FC<RouteComponentProps<Params>>.


推荐阅读