与props只能逐级传递数据相比,使用context可以实现跨级传递数据。
下面通过一个demo来展示context传递数据的实现:
//父组件,最上层的组件
import React,{ Component,PropTypes } from 'react';
import Son from './Son';
class App extends Component {
getChildContext() {
return {test: "hello"};
}
render() {
return (
<div className="App" style={{border:'1px solid red',width:'30%',margin:'50px auto',textAlign:'center'}}>
<p style={{padding:'0',margin:'0'}}>父组件</p>
<Son/>
</div>
);
}
}
App.childContextTypes = {
test: PropTypes.string
};
export default App;
//子组件
import React,PropTypes } from 'react';
import Grandson from './Grandson';
class App extends Component {
render() {
console.log('this.context',this.context);
return (
<div className="son" style={{border:'1px solid blue',width:'60%',textAlign:'center'}}>
<p>子组件,获取父组件的值:{this.context.test}</p>
<Grandson/>
</div>
);
}
}
App.contextTypes = {
test: PropTypes.string
};
export default App;
//孙组件
import React,PropTypes } from 'react';
class App extends Component {
render() {
console.log('this.context:',this.context);
return (
<div className="son" style={{border:'1px solid green',textAlign:'center'}}>
<p>孙组件,获取传递下来的值:{this.context.test}</p>
</div>
);
}
}
App.contextTypes = {
test: PropTypes.string
};
export default App;
最终实现效果如下图