我在用于创建药物实例的反应项目中有一个简单的非反应性ES6类。

export default class Medication {
  constructor(props) {
    ...
  }
  someFunction() {}
}

const medData = [{name: "med1"}, {name: "med2"}, {name: "med3"}];
const meds = medData.map(med => new Medication(med));

我还有一个设置上下文或提供程序,用于保留从后端加载一次并通过上下文提供设置的设置。
export const SettingContext = React.createContext();

export default class SettingsProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {settings: {...}};
  }
  ...
  render() {
    return (
        <SettingContext.Provider value={{setting: this.state.settings}}>
          {this.props.children}
        </SettingContext.Provider>
    );
  }
}


有没有办法在Medication类中使用此上下文,以便可以在其中使用设置?在可以使用上下文的ES6类之外,还有什么替代方法?

最佳答案

创建上下文文件

//context.jsx
import React from "react";
export const initialSetting = { foo: true };
export const SettingContext = React.createContext({
  settings: initialSetting,
  setSettings: () => {}
});

然后创建高阶组件

//HocModule.jsx
import React from "react";
import { SettingContext } from "./context.jsx";
export const HocModule = props => {
  const [settings, setSettings] = React.useState();
  const settingsValue = React.useMemo(() => ({ settings, setSettings }), [
    settings,
    setSettings
  ]);

  return (
    <SettingContext.Provider value={settingsValue}>
      {props.children}
    </SettingContext.Provider>
  );
};


现在,任何模块都可以设置上下文

//AnyModule.jsx

import { SettingContext } from "./context.jsx";
import { HocModule } from "./HocModule";

export const AnyModule = () => {
  const { settings, setSettings } = React.useContext(SettingContext);
  return (
    <HocModule>
      <div>{JSON.stringify(settings)}</div>
    </HocModule>
  );
};

export default AnyModule;

09-11 19:50