首页 > 解决方案 > 在 typescript 中为 JSX.Element 添加更多道具

问题描述

我将 TypeScript 与 React 一起使用,并且我想将 userId 道具传递给渲染的每个组件。我不想userId为每个单独的组件添加道具,并且无法弄清楚如何使每个 React 组件都具有道具。

为了让这一切变得更加困难,现在它给了我一个 TS 错误JSX element type 'Component' does not have any construct or call signatures.

我将如何使这一切正常工作?


type Props = {
  children: JSX.Element;

  // I have tried many different things, but nothing worked...
  // React.ComponentType<{ user: PartialUser }>;
  
};

type PartialUser = {
  id: number;
  username: string;
  email: string;
};

const PrivateRoute = ({ children, ...rest }: Props) => {
  const { data, error, loading } = useMeQuery();

  let me;
  let user;
  if (data?.me) {
    me = data!.me!;

    user = {
      id: me.id,
      username: me.username,
      email: me.email,
    };
  }

  if (error) console.error(error);
  const Component = children;
  return (
    <>
      {!loading && user ? (
        <Route {...rest}>
          <Component user={user} />
        </Route>
      ) : (
        <Redirect to="/login" />
      )}
    </>
  );
};

标签: reactjstypescriptreact-routerreact-router-dom

解决方案


那么您可以做的另一种方法是使用 Context API。查看https://reactjs.org/docs/context.html#when-to-use-context以获得更多理解

我要做的是创建一个包含用户 ID 的自定义类型,然后使用该类型创建反应上下文。

现在下一步将使用此上下文并创建一个提供程序,然后在此上下文提供程序中呈现必要的组件。然后,您可以在嵌套在此自定义创建的上下文中的任何深层的任何子组件中使用此上下文,并且您可以获得用户 ID。

例如。

创建自定义上下文类型和反应上下文:

export type MyContextType = {
    userId: number
}

export const MyContext = React.createContext<MyContextType>(undefined!);

现在使用提供程序并在您的主/根文件中传递初始值

const context: MyContextType = {
     userId: 1 (I am assuming you would get this from API response or local storage)
};
<MyContext.Provider value={context}>
    ...nested components
    <MyComponent />
</MyContext.Provider>

然后在您的任何嵌套组件中,您可以使用以下方法获取此上下文和值:

class MyComponent extends React.Component<MyComponentProps, State> {
    static contextType = MyContext;
    context!: React.ContextType<typeof MyContext>;

    render() {
       console.log(this.context.userId); // You should be able to see 1 being printed in the console.
    }
}

推荐阅读