React Context
如何使用Context
context api给出三个概念:React.createContext()、Provider、Consumer;
React.createContext()
这个方法用来创建context对象,并包含Provider、Consumer两个组件 <Provider />、<Consumer />
const {Provider, Consumer} = React.createContext();
Provider
数据的生产者,通过value属性接收存储的公共状态,来传递给子组件或后代组件
eg:
<Provider value={/* some value */}>
Consumer
数据的消费者,通过订阅Provider传入的context的值,来实时更新当前组件的状态
eg:
<Consumer>
{value => /* render something based on the context value */}
</Consumer>
使用方法
App.js
import React from 'react'
import Son from './son.js'
import './App.css';
export const {Provider,Consumer} = React.createContext('默认名称');
function App() {
let name = '小孩子';
return (
<Provider value={name}>
<div style={{border:'1px solid red'}}>
<p>父组件定义的: {name}</p>
<Son/>
</div>
</Provider>
);
}
export default App;
son.js
import React from 'react'
import {Consumer} from './App'
import GrandSon from './grandSon'
function Son (props){
return (
<Consumer>
{
(name)=>
<div>
子组件: {name}
<GrandSon/>
</div>
}
</Consumer>
)
}
export default Son
grandSon.js
import React from 'react'
import {Consumer} from './App'
function GrandSon (){
return (
//消费使用
<Consumer>
{(name)=>
<div>
这个是孙组件: {name}
</div>
}
</Consumer>
)
}
export default GrandSon
组件最终显示结果