Context API是一种在整个应用中传递状态而无需使用道具的巧妙方法。
Context API的引入是为了让你在整个应用中传递状态(并使状态得到更新),而不必使用props。
React团队建议,如果你只有几层的孩子需要传递,就坚持使用props,因为它仍然是一个比Context API复杂得多的API。
在很多情况下,它使我们能够避免使用Redux,将我们的应用程序简化了很多,同时也学会了如何使用React。
它是如何工作的?
你使用React.createContext() 创建一个上下文,它返回一个Context对象。
const { Provider, Consumer } = React.createContext()
然后你创建一个包装组件,它返回一个提供者组件,你把所有你想访问上下文的组件作为子组件加入。
class Container extends React.Component {
constructor(props) {
super(props)
this.state = {
something: 'hey'
}
}
render() {
return (
<Provider value={{ state: this.state }}>{this.props.children}</Provider>
)
}
}
class HelloWorld extends React.Component {
render() {
return (
<Container>
<Button />
</Container>
)
}
}
我使用Container作为这个组件的名字,因为这将是一个全局提供者。你也可以创建更小的上下文。
在一个被提供者包裹的组件中,你可以使用一个消费者组件来使用上下文。
class Button extends React.Component {
render() {
return (
<Consumer>
{context => <button>{context.state.something}</button>}
</Consumer>
)
}
}
你也可以把函数传给提供者的值,这些函数将被消费者用来更新上下文的状态。
<Provider value={{
state: this.state,
updateSomething: () => this.setState({something: 'ho!'})}}>
{this.props.children}
</Provider>
/* ... */
<Consumer>
{(context) => (
<button onClick={context.updateSomething}>{context.state.something}</button>
)}
</Consumer>
你可以在这个Glitch中看到这个动作。
你可以创建多个上下文,使你的状态分布在不同的组件中,但又将其公开,使其可以被任何你想要的组件接触到。
当使用多个文件时,你在一个文件中创建内容,并在你使用它的所有地方导入它。
//context.js
import React from 'react'
export default React.createContext()
//component1.js
import Context from './context'
//... use Context.Provider
//component2.js
import Context from './context'
//... use Context.Consumer