博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
React小技巧: 使用Context跨组件树传递数据
阅读量:7047 次
发布时间:2019-06-28

本文共 2715 字,大约阅读时间需要 9 分钟。

clipboard.png

没有使用Context的情况下传递数据, 我们可以参考React的文档: , 它是通过组件属性一级一级往下传递. 这种方式很麻烦, 如果组件树比较深, 必须在每一个路径上的节点都引入不必要的属性.

定义 Context 的根组件

import React      from 'react';# React 15.5版本以后, 使用PropTypes需要引入外部库, 直接使用React.PropTypes 会抛警告import PropTypes from 'prop-types';# React Router V4版本要从 react-router-dom 导入需要的组件import { Route, Link } from 'react-router-dom';import { Row, Col, Menu, Icon, Dropdown, Layout} from 'antd';const { Sider, Content } = Layout;import UserList   from './UserList';import UserDetail from './UserDetail';import Sidebar    from '../_layouts/Sidebar';const avatars = [  "elyse.png",  "kristy.png",  "matthew.png",];const data = [];for(let i = 0; i <= avatars.length; i++){  data.push({key: i, name: '胡彦祖3',age: 42,address: '西湖区湖底公园1号'});}const columns = [  { title: 'ID',dataIndex: 'key',key: 'key'},  { title: '姓名',dataIndex: 'name',key: 'name', render: function(text, record, index) {    return (
{text}
) }}, { title: '年龄',dataIndex: 'age',key: 'age'}, { title: '住址',dataIndex: 'address',key: 'address'}, { title: 'Action', key: 'action', render: function(text, record, index){ return (
) } }];class UserIndex extends React.Component { constructor(props){ super(props) } # 定义Context需要实现的方法 getChildContext() { return { data: data, columns: columns }; } render(){ return (

用户信息页

) }}# 声明Context类型UserIndex.childContextTypes = { data: PropTypes.array, columns: PropTypes.array,};export default UserIndex;

中间组件

中间中间不再通过组件属性一级一级的往下传递了. 我们这里在 render() 函数中定义一个空的 <List/>:

import React from 'react';import PropTypes from 'prop-types';import { Table, Icon } from 'antd';import {  Link} from 'react-router-dom';import List from '../_common/List';class UserList extends React.Component {  constructor(props){    super(props)  }  render(){    return (      
) }}export default UserList;

子组件, 列表

import React from 'react';import PropTypes from 'prop-types';import { Layout, Table } from 'antd';const { Sider, Content } = Layout;class List extends React.Component {  constructor(props) {    super(props);  }  render() {    return (      
); }}List.propTypes = { data: PropTypes.array, columns: PropTypes.array};# 在这里声明 contextTypes 用于访问 UserIndex 组件中定义的Context数据.List.contextTypes = { data: PropTypes.array, columns: PropTypes.array};export default List;

转载地址:http://snkol.baihongyu.com/

你可能感兴趣的文章
RESTful 接口请求报数组越界
查看>>
我的友情链接
查看>>
单链表(C语言)
查看>>
linux目录结构
查看>>
Guarded Suspension
查看>>
centos7.5 安装git客户端
查看>>
搞大数据,需要关注的东西
查看>>
win平台安装gridcontrol11R1的agent
查看>>
Docker image的工作原理
查看>>
CDH使用
查看>>
Hadoop源代码分析(Task的内部类和辅助类)
查看>>
Baruch Computing and Technology Center (BCTC)
查看>>
rehhat5.5搭建各种dns服务器(4)
查看>>
set unused的用法(ORACLE删除字段)
查看>>
计算机专用英语词汇1695个词汇表
查看>>
致敬那些运维过程中踩到的坑
查看>>
MySQL concat函数的使用
查看>>
JS 生成名片、链接等二维码
查看>>
腾讯-开源版蓝鲸智云配置平台试用
查看>>
bonding
查看>>