【问题标题】:React Typescript, how to use Context?React Typescript,如何使用上下文?
【发布时间】:2022-01-11 09:07:37
【问题描述】:

我有一个超级简单的应用,比如

import React, { createContext } from 'react';
import { render } from 'react-dom';
import './style.css';

interface IAppContext {
  name: string;
  age: number;
  country: string;
}

const AppContext = createContext<IAppContext | null>(null);

const App = () => {

  const contentValue: IAppContext = {
    name: 'Paul',
    age: 21,
    country: 'UK',
  };

  return (
    <AppContext.Provider value={contentValue}>
      <div>{name}</div>
    </AppContext.Provider>
  );
};

render(<App />, document.getElementById('root'));

我只是想使用上下文,但在 &lt;div&gt;{name}&lt;/div&gt; 中出现错误

'name' is deprecated.(6385)
lib.dom.d.ts(19534, 5): The declaration was marked as deprecated here.
Type 'void' is not assignable to type 'ReactNode'.(2322)
index.d.ts(1183, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
const name: void
@deprecated 

这是使用上下文的正确方法吗?

是我使用打字稿的方式导致了这个错误吗?

【问题讨论】:

  • 错误与上下文无关。 name 来自哪里?

标签: reactjs typescript


【解决方案1】:

通常你会使用 useContext。但是在您当前的示例中,您可以通过将name 更改为contentValue.name 来直接使用对象值。

进一步说明;

上下文提供者允许您使用称为useContext 的钩子访问上下文提供者的值。当你调用这个钩子时,你传入了你希望定位的上下文。在这种情况下,它将是useContext(AppContext)。这使您可以访问&lt;AppContext.Provider /&gt;value 属性,在您的情况下,此值等于contentValue

示例;

const MyComponent = () => {

  const appContext = useContext(AppContext);

  return (
    <div>
      {appContext.name}
   </div>
  )
}

【讨论】:

    【解决方案2】:

    Context 基本上是一个非常简单的状态管理工具。简而言之,如果您有一个初始化了某个状态的父组件,那么在子组件中访问此状态所需要做的就是将其作为 props 传递。如果您有 10 个子组件,则必须手动执行 10 次,这不太实用。 所以 useContext 基本上扭曲了父组件,每个子组件都可以访问该上下文。 在你的情况下:

    interface IAppContext {
      name: string;
      age: number;
      country: string;
    }
    
    const AppContext = createContext<IAppContext | null>(null);
    
    const App = () => {
    
      const contentValue: IAppContext = {
        name: 'Paul',
        age: 21,
        country: 'UK',
      };
    
      return (
        <AppContext.Provider value={contentValue}>
          <ChildComponent/> // now let's say you another child component here.
        </AppContext.Provider>
      );
    };
    
    const ChildComponent = () => {
      const appContext = useContext(AppContext);
      return <div>appContext.name</div>
    }
    export default Home
    

    如您所见,您也可以访问子组件中的上下文。

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 2020-10-04
      • 2020-08-03
      • 2020-07-11
      • 2019-12-15
      • 1970-01-01
      • 2021-04-14
      • 2021-05-22
      • 2017-12-29
      相关资源
      最近更新 更多