本文共 2715 字,大约阅读时间需要 9 分钟。
The Context API was introduced to allow you to pass state (and enable the state to update) across the app, without having to use props for it.
引入Context API是为了允许您在应用程序之间传递状态(并使状态得以更新),而不必为此使用道具。
The React team suggests to stick to props if you have just a few levels of children to pass, because it’s still a much less complicated API than the Context API.
如果您只有几个级别的孩子要通过,React团队建议坚持使用道具,因为它仍然比Context API复杂得多。
In many cases, it enables us to avoid using , simplifying our apps a lot, and also learning how to use React.
在许多情况下,它使我们能够避免使用 ,从而大大简化了我们的应用程序,并了解了如何使用React。
How does it work?
它是如何工作的?
You create a context using React.createContext()
, which returns a Context object.:
使用React.createContext()
创建一个上下文,该上下文返回一个Context对象。
const { Provider, Consumer } = React.createContext()
Then you create a wrapper component that returns a Provider component, and you add as children all the components from which you want to access the context:
然后,创建一个返回Provider组件的包装器组件,并将要访问其上下文的所有组件添加为子组件:
class Container extends React.Component { constructor(props) { super(props) this.state = { something: 'hey' } } render() { return ({this.props.children} ) }}class HelloWorld extends React.Component { render() { return () }}
I used Container as the name of this component because this will be a global provider. You can also create smaller contexts.
我使用Container作为该组件的名称,因为这将是一个全局提供程序。 您还可以创建较小的上下文。
Inside a component that’s wrapped in a Provider, you use a Consumer component to make use of the context:
在包装在Provider中的组件内部,您可以使用Consumer组件来利用上下文:
class Button extends React.Component { render() { return ({context => } ) }}
You can also pass functions into a Provider value, and those functions will be used by the Consumer to update the context state:
您还可以将函数传递到Provider值中,并且Consumer将使用这些函数来更新上下文状态:
this.setState({something: 'ho!'})}}> {this.props.children} /* ... */{(context) => ( )}
You can see this in action .
您可以看到这 。
You can create multiple contexts, to make your state distributed across components, yet expose it and make it reachable by any component you want.
您可以创建多个上下文,以使您的状态分布在各个组件之间,同时公开它并使任何所需的组件都可以访问它。
When using multiple files, you create the content in one file, and import it in all the places you use it:
使用多个文件时,可以在一个文件中创建内容,然后将其导入所有使用位置:
//context.jsimport React from 'react'export default React.createContext()//component1.jsimport Context from './context'//... use Context.Provider//component2.jsimport Context from './context'//... use Context.Consumer
翻译自:
转载地址:http://bmqgb.baihongyu.com/