为什么我需要新的Context API?该值已导入

问题描述 投票:0回答:1

新的Context API要求使用者从创建它的位置导入上下文。

那么为什么消费者需要定义contextType?我可以使用导入的值。

import ThemeContext from './context/theme';

class Component {
  render() {
    return (
      <div>{this.context}</div>
    );
  }
}

Consumer.contextType = ThemeContext; // why?

如果我在包ComponentA中有一个组件PackageA,它需要一个上下文。如何为它定义上下文?

// PackageA/ComponentA.js, managed by npm/yarn
import PackageContext from './context';

class ComponentA {}

ComponentA.contextType = PackageContext;

// ===========================================

// src/App.js
import ComponentA from 'PackageA/ComponentA';

const MyContext = React.createContext();

function App() {
  return (
    <MyContext.Provider value="app context">
      <ComponentA />
    </MyContext.Provider>
  );
}

我出现的唯一方法就是这样。但我真的不喜欢它。

// src/ComponentA.js
import ComponentA from 'PackageA/ComponentA';

ComponentA.contextType = MyContext;

export default ComponentA;

// And just import this component instead of the one in `PackageA`,
// although we can still use it because it's modified.
reactjs
1个回答
1
投票

contextType static property应该与context实例属性一起用于类组件,并作为ThemeContext.Consumer的替代。如果功能组件没有任何影响,则不需要Consumer.contextType

功能组件中contextType的对应物是useContext hook,因为React 16.8:

function Consumer() {
  const theme = React.useContext(ThemeContext);
  return (
    <div>{theme}</div>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.