//首先新建一个公共js context.js 解构出一个Provider和Consumer并导出
import React,{createContext} from 'react'
const {Provider,Consumer} =createContext()
export {
Provider,Consumer
}
//在需要用这对组件的页面再分别引入Provider,Consumer
根组件
import React, { Component } from 'react';
import Two from './Two';
import { Provider } from './context';
export default class One extends Component {
state = {
name: '西瓜'
}
render() {
return (
<Provider value={this.state.name}>
1
<Two />
</Provider>
)
}
}
中间组件
import React, { Component } from 'react';
import Three from './Three';
export default class Two extends Component {
render() {
return (
<div>
2
<Three></Three>
</div>
)
}
}
需要传值的组件
import React, { Component } from 'react';
import { Consumer } from './context.js';
export default class Three extends Component {
render() {
return (
<Consumer>
{
(data) => {
return <div>3{data}</div>
}
}
</Consumer>
)
}
}