1

我正在试验反应上下文 API,这是我正在处理的代码:

import * as React from 'react';

interface ProviderState {
  themeColor: string;
}

interface UpdateStateArg {
  key: keyof ProviderState;
  value: string;
}

interface ProviderStore {
  state: ProviderState;
  update: (arg: UpdateStateArg) => void;
}

const Context = React.createContext({} as ProviderStore);

class Provider extends React.Component<{}, ProviderState> {
  readonly state = {
    themeColor: 'red'
  };

  private update = ({ key, value }: UpdateStateArg) => {
    this.setState({ [key]: value });
  }

  render() {
    const store: ProviderStore = {
      state: this.state,
      update: this.update
    };

    return (
      <Context.Provider value={store}>
         {this.props.children}
      </Context.Provider>
    );
  }
}

export { Provider };

渲染方法中的“提供者”引发以下错误:

在此处输入图像描述

"JSX element type 'ReactElement<any> | null' is not a constructor function for JSX elements.Type 'null' is not assignable to type 'ElementClass"

在反应声明文件中'Provider'已被声明,我认为它已被正确声明,或者我可能错了!

我正在使用以下版本:

react: "^16.5.0"
react-dom: "^16.5.0"
@types/react: "^16.4.7"
@types/react-dom: "^16.0.7"
4

0 回答 0