React之使用context传递数据
来源:互联网 发布:mac战网国服改台服 编辑:程序博客网 时间:2024/06/17 01:22
与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, { Component,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%',margin:'50px auto',textAlign:'center'}}> <p>子组件,获取父组件的值:{this.context.test}</p> <Grandson/> </div> ); }}App.contextTypes = { test: PropTypes.string};export default App;
//孙组件import React, { Component,PropTypes } from 'react';class App extends Component { render() { console.log('this.context:',this.context); return ( <div className="son" style={{border:'1px solid green',width:'60%',margin:'50px auto',textAlign:'center'}}> <p>孙组件,获取传递下来的值:{this.context.test}</p> </div> ); }}App.contextTypes = { test: PropTypes.string};export default App;
最终实现效果如下图
阅读全文
0 0
- React之使用context传递数据
- react之使用Context跨组件树传递数据
- React数据传递---context
- react学习之路(2.2)-----数据传递(props(子传父级),context)
- Context 传递数据(转载)
- Context 传递数据
- react 数据传递
- React数据传递-state
- react数据传递----props
- React 中 context 的使用
- react-redux中的数据传递
- react---组件间数据传递
- 续-React数据传递-props
- React 的数据载体:state、props、context
- react笔记-数据载体state/props/context
- react native使用react-navigation跳转后多页面数据传递总结
- React+DvaJs 之 Context与Props
- Android中在Activity之间传递数据的另一种方法, 使用application context
- php如何使用自动加载(重写url形成单一入口)
- 简单的Html和JavaScript:用户注册页面
- elasticsearch插件安装
- 基础复习
- retrofit框架使用
- React之使用context传递数据
- 继续努力
- Android进程间通信
- 1037: [ZJOI2008]生日聚会Party dp
- MATLAB GUI设计的大小控制参数units
- hystrix的超时含义
- jquery.lazyload 懒加载
- Spark---Word Count
- 34 linux系统管理