没有使用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;