1
1
// highlight-range{1-4}
2
- // Context lets us pass a value deep into the component tree
3
- // without explicitly threading it through every component.
4
- // Create a context for the current theme (with "light" as the default).
2
+ // Context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。
3
+ // 为当前的 theme 创建一个 context(“light”为默认值)。
5
4
const ThemeContext = React . createContext ( 'light' ) ;
6
5
7
6
class App extends React . Component {
8
7
render ( ) {
9
8
// highlight-range{1-3,5}
10
- // Use a Provider to pass the current theme to the tree below.
11
- // Any component can read it, no matter how deep it is.
12
- // In this example, we're passing " dark" as the current value.
9
+ // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。
10
+ // 无论多深,任何组件都能读取这个值。
11
+ // 在这个例子中,我们将 “ dark” 作为当前的值传递下去。
13
12
return (
14
13
< ThemeContext . Provider value = "dark" >
15
14
< Toolbar />
@@ -19,8 +18,7 @@ class App extends React.Component {
19
18
}
20
19
21
20
// highlight-range{1,2}
22
- // A component in the middle doesn't have to
23
- // pass the theme down explicitly anymore.
21
+ // 中间的组件再也不必指明往下传递 theme 了。
24
22
function Toolbar ( props ) {
25
23
return (
26
24
< div >
@@ -31,9 +29,9 @@ function Toolbar(props) {
31
29
32
30
class ThemedButton extends React . Component {
33
31
// highlight-range{1-3,6}
34
- // Assign a contextType to read the current theme context.
35
- // React will find the closest theme Provider above and use its value.
36
- // In this example, the current theme is " dark".
32
+ // 指定 contextType 读取当前的 theme context。
33
+ // React 会往上找到最近的 theme Provider,然后使用它的值。
34
+ // 在这个例子中,当前的 theme 值为 “ dark”。
37
35
static contextType = ThemeContext ;
38
36
render ( ) {
39
37
return < Button theme = { this . context } /> ;
0 commit comments