用泛型反应上下文

时间:2020-03-17 15:39:29

标签: reactjs typescript generics react-context

我们如何在React.CreateContext中使用泛型?

我有这个:

interface Props {
}

export interface SearchContextProps {
  dtos: any[];
}

export const SearchContext = React.createContext<SearchContextProps>({
  dtos: []
});

const SearchPage: React.FunctionComponent<Props> = (props) => {
  const [dtos, setDtos] = React.useState<any[]>([]);

  const searchContext = {
    dtos: dtos
  };

  return (
    <SearchContext.Provider value={searchContext}>
      ...
    </SearchContext.Provider>
  );
}

export default SearchPage;

现在我想使用泛型,所以我会写类似的东西:

interface Props<T> {
}

export interface SearchContextProps<T> {
  dtos: T[];
}

export const SearchContext = React.createContext<SearchContextProps<T>>({
  dtos: []
});

const SearchPage = <T extends object>(props: Props<T>) => {
  const [dtos, setDtos] = React.useState<T[]>([]);

  const searchContext = {
    dtos: dtos
  };

  return (
    <SearchContext.Provider value={searchContext}>
      ...
    </SearchContext.Provider>
  );
}

export default SearchPage;

但是我不知道如何开始工作:

export const SearchContext = React.createContext<SearchContextProps<T>>({

如何在此处使用泛型?如何访问T?

我试图在组件内部移动上下文:

interface Props<T> {
}

export interface SearchContextProps<T> {
  dtos: T[];
}

const SearchPage = <T extends object>(props: Props<T>) => {
  const [dtos, setDtos] = React.useState<T[]>([]);

  const SearchContext = React.createContext<SearchContextProps<T>>({
    dtos: [],
  });

  const searchContext = {
    dtos: dtos,
  };

  return (
    <SearchContext.Provider value={searchContext}>
      ...
    </SearchContext.Provider>
  );

}

export default SearchPage;

但是现在我不知道如何导出它。

有帮助吗?

2 个答案:

答案 0 :(得分:0)

我最终得到:

import * as React from 'react';

interface Props<T> {}

export interface SearchContextProps<T> {
  dtos: T[];
}

export const SearchContext = React.createContext<SearchContextProps<any>>({
  dtos: [],
});

const SearchPage = <T extends object>(props: React.PropsWithChildren<Props<T>>) => {
  const [dtos, setDtos] = React.useState<T[]>([]);

  const searchContext = {
    dtos: dtos,
  };

  return <SearchContext.Provider value={searchContext}>...</SearchContext.Provider>;
};

export default SearchPage;

但是我现在不知道如何写一个消费者。

答案 1 :(得分:0)

我也一直试图弄清楚这一点,终于用我正在构建atm的向导来做到了。

提供者部分与您相似:

import React, { Dispatch, SetStateAction } from "react";

export interface IWizardContext<T> {
  formData: T;
  setFormData: Dispatch<SetStateAction<T>>;
}

export const WizardContext = React.createContext<IWizardContext<any>>({
  formData: {},
  setFormData: () => {},
});

const WizardProvider: React.FC = (props) => {
  const [formData, setFormData] = React.useState<any>({});

  return (
    <WizardContext.Provider
      value={{
        formData: formData,
        setFormData: setFormData,
      }}
    >
      {props.children}
    </WizardContext.Provider>
  );
};

export default WizardProvider;

export function withWizardProvider<TProps = {}>(component: React.FC<TProps>) {
  const Component = component;

  return ((props: TProps) => {
    return (
      <WizardProvider>
        <Component {...props} />
      </WizardProvider>
    );
  }) as React.FC<TProps>;
}

和消费者:

import React from "react";
import {
  IWizardContext,
  withWizardProvider,
  WizardContext,
} from "./WizardProvider";

interface ISampleWizardState {
  name?: string;
  lastName?: string;
}

const SampleWizard: React.FC = (props) => {
  const wizard = React.useContext<IWizardContext<ISampleWizardState>>(
    WizardContext
  );

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "flex-start",
        flexDirection: "column",
      }}
    >
      <span>{`${wizard.formData.name || "John"} ${
        wizard.formData.lastName || "Doe"
      }`}</span>
      <input
        type="text"
        name="name"
        value={wizard.formData.name}
        onChange={(e) => {
          const text = e?.target?.value;
          wizard.setFormData((prev) => ({
            ...prev,
            name: text,
          }));
        }}
      />
      <input
        type="text"
        name="lastName"
        value={wizard.formData.lastName}
        onChange={(e) => {
          const text = e?.target?.value;
          wizard.setFormData((prev) => ({
            ...prev,
            lastName: text,
          }));
        }}
      />
    </div>
  );
};

export default withWizardProvider(SampleWizard);

因此,对于消费者而言,最主要的是在useContext中定义您的T:

React.useContext<IWizardContext<ISampleWizardState>>(WizardContext);