简介
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
在典型的React应用程序中,数据通过props自上而下传递(父对象),但这对于应用程序中许多组件所需的某些类型的props(例如区域设置首选项,UI主题)来说可能很麻烦。 Context提供了一种在组件之间共享这些值的方法,而无需通过树的每个级别显式传递prop。
手动一级级传递props:
class App extends React.Component { render() { return <Toolbar theme="dark" />; } } function Toolbar(props) { // The Toolbar component must take an extra "theme" prop // and pass it to the ThemedButton. This can become painful // if every single button in the app needs to know the theme // because it would have to be passed through all components. return ( <div> <ThemedButton theme={props.theme} /> </div> ); } class ThemedButton extends React.Component { render() { return <Button theme={this.props.theme} />; } }
使用Context,通过中间元素避免传递props:
// Context lets us pass a value deep into the component tree // without explicitly threading it through every component. // Create a context for the current theme (with "light" as the default). const ThemeContext = React.createContext('light'); class App extends React.Component { render() { // Use a Provider to pass the current theme to the tree below. // Any component can read it, no matter how deep it is. // In this example, we're passing "dark" as the current value. return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); } } // A component in the middle doesn't have to // pass the theme down explicitly anymore. function Toolbar(props) { return ( <div> <ThemedButton /> </div> ); } class ThemedButton extends React.Component { // Assign a contextType to read the current theme context. // React will find the closest theme Provider above and use its value. // In this example, the current theme is "dark". static contextType = ThemeContext; render() { return <Button theme={this.context} />; } }
上下文主要用于一些数据需要被不同层级的组件访问。小心使用,因为它会增加组件复用的难度。