Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行跨层级数据传递的方法,它设计目的就是为了共享那些对于一个组件树而言是“全局”的数据
一. 式例1
1. 目录结构
2. 基本使用
global.js:
import React from "react";
export const globalData = {
a: 1
}
export const globalContext = React.createContext(globalData);
/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
<style>
.app {
border: 1px solid red;
padding: 30px
}
.father {
border: 1px solid blue;
padding: 30px
}
.son {
border: 1px solid pink;
padding: 30px
}
</style>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
App.js:
import React, {
Component }</