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

时间:2019-02-18 09:23:45

标签: reactjs

新的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.

1 个答案:

答案 0 :(得分:1)

contextType static property应该与类组件以及context实例属性一起使用,并且可以作为ThemeContext.Consumer的替代。如果功能组件不受影响,则不需要Consumer.contextType

从功能16.8开始,功能组件中与contextType相对的是useContext hook

function Consumer() {
  const theme = React.useContext(ThemeContext);
  return (
    <div>{theme}</div>
  );
}