**context的基本使用新版**
**1、全局定义context对象**
globalContext.js
import React from "react";
const GlobalContext = React.createContext();
export default GlobalContext;
**2、根组件引入GlobalContext,并使用GlobalContext.Provider(生产者环境)**
import React, { Component ,Fragment} from 'react';
import One from "./components/one";
import GlobalContext from "./globalContext";
class App extends Component {
render() {
return (
<GlobalContext.Provider
value={{
name:"zhangsan",
age:19
}}
>
<One/>
</GlobalContext.Provider>
);
}
}
export default App;
**3、组件引入GlobalContext并调用context,使用GlobalContext.Consumer**
import React, { Component } from 'react'
import GlobalContext from "../globalContext";
export default class One extends Component {
render() {
return (
<GlobalContext.Consumer>
{
context => {
console.log(context)
return (
<div>
<h2>{context.name}</h2>
<h2>{context.age}</h2>
</div>
)
}
}
</GlobalContext.Consumer>
)
}
}
``
react context新版本(2) 代码
最新推荐文章于 2024-03-04 10:10:33 发布