gpt4 book ai didi

javascript - React TypeScript HoC - 将组件作为 Prop 传递

转载 作者:可可西里 更新时间:2023-11-01 02:24:23 24 4
gpt4 key购买 nike

遵循本教程:https://reacttraining.com/react-router/web/example/auth-workflow .

尝试重现代码:

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);

在 typescript 中:

import * as React from 'react';
import { Route, RouterProps } from 'react-router';

interface Props extends RouterProps {
component: React.Component;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
<Route
{...rest}
render={(props) => <Component {...props} />}
/>
);
};

export default PrivateRoute;

但它总是会失败。尝试了不同的变化。我发布的是最新的一个。获取:

enter image description here

在我看来,我必须为 Component 类型传递 Generic,但我不知道如何。

编辑:

目前最接近的解决方案:

interface Props extends RouteProps {
component: () => any;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
<Route
{...rest}
render={(props) => <Component {...props} />}
/>
);
};

然后:

<PrivateRoute component={Foo} path="/foo" />

最佳答案

您想传递一个组件构造函数,而不是一个组件实例:

import * as React from 'react';
import { Route, RouteProps } from 'react-router';

interface Props extends RouteProps {
component: React.ComponentType;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
return (
<Route
{...rest}
render={(props) => <Component {...props} />}
/>
);
};

export default PrivateRoute;

class Foo extends React.Component {

}
let r = <PrivateRoute component={Foo} path="/foo" />

编辑

更完整的解决方案应该是通用的并使用RouteProps代替RouterProps:

import * as React from 'react';
import { Route, RouteProps } from 'react-router';

type Props<P> = RouteProps & P & {
component: React.ComponentType<P>;
}

const PrivateRoute = function <P>(p: Props<P>) {
// We can't use destructuring syntax, because : "Rest types may only be created from object types", so we do it manually.
let rest = omit(p, "component");
let Component = p.component;
return (
<Route
{...rest}
render={(props: P) => <p.component {...props} />}
/>
);
};

// Helpers
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
function omit<T, TKey extends keyof T>(value:T, ... toRemove: TKey[]): Omit<T, TKey>{
var result = Object.assign({}, value);
for(let key of toRemove){
delete result[key];
}
return result;
}


export default PrivateRoute;

class Foo extends React.Component<{ prop: number }>{

}
let r = <PrivateRoute component={Foo} path="/foo" prop={10} />

关于javascript - React TypeScript HoC - 将组件作为 Prop 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274143/

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