//main.js
import { FileContext } from './FileContext';
export default class Main extends React.Component {
render() {
const fileName = 'a-file'
<FileContext.Provider value = {fileName} >
// do smt, include Show Component(<Show />)
</FileContext.Provider>
}
}
//Show.js
import {FileContext} from './FileContext';
export default class Show extends React.Component {
render() {
<FileContext.Consumer >
{
(fileName) => //do smt, this fileName is from main context
}
</FileContext.Consumer>
}
}
上面的就是目前16.x版本的用法,下面来看看之前的context如何使用。
旧版的context
// main.js
import React from 'react';
import { PropTypes } from 'prop-types';
export default class Main extends from React.Component {
render() {
// do smt, include foo component, likes: <Foo />
}
}
Main.childContextTypes = {
fileNmae: PropTypes.string
};
// foo.js
import React from 'react';
import { PropTypes } from 'prop-types';
export default class Foo extends React.Component {
constructor(props, context){
super(props, context)
console.log('context is --', context)
}
render() {
return(<h1>Hi, {this.props.context}</h1>)
}
}
Foo.contextTypes = {
fileName: PropTypes.string
};