react兄弟组件之间的传值

react兄弟组件之间的传值

一.通过redux

1.在redux中找到对应的文件设置

a.
react兄弟组件之间的传值_第1张图片
b.
react兄弟组件之间的传值_第2张图片
c.
react兄弟组件之间的传值_第3张图片
d.
react兄弟组件之间的传值_第4张图片

2.页面存储数据到redux中
react兄弟组件之间的传值_第5张图片
3.页面提取redux里面的数据
react兄弟组件之间的传值_第6张图片

二.通过hook中的createContext来实现

1.父组件中的写法

import React, { memo, useState } from 'react'
import { Row, Col } from 'antd';
import Department from "@/container/setModule/department";
import UserList from "@/container/setModule/userList";
import { useSetState } from '@/hooks'

export const userManageContext = React.createContext();

const UserManage = memo(function UserManage(props) {

  const [userManageData, setUserManageData] = useState();
  const UserManageContextProps = {
    userManageData,
    setUserManageData
  }
  return (
    <div className="bgW padding-20px">
      <Row>
        <userManageContext.Provider value={UserManageContextProps}>
          <Col span={4}>
            <Department />
          </Col>
          <Col span={20} style={{ paddingLeft: '10px', boxSizing: 'border-box' }}>
            <UserList />
          </Col>
        </userManageContext.Provider>
      </Row>
    </div>
  )
})

export default UserManage

2.Department子组件中的写法

import React, { memo, useState, useEffect, useContext, useRef, useMemo } from 'react'
import { useAsync } from '@/hooks'
import { Input, Menu, Tree } from 'antd';
import { treelist } from '@/api/set'
import { requestCode } from '@/utils/varbile'
import { userManageContext } from '@/pages/set/userManage'
import { DownOutlined } from '@ant-design/icons';
import RouterLoading from "@/components/routerLoading";

const Department = memo(function Department(props) {
  const reviceProps = useContext(userManageContext);
  const { Search } = Input;
  const [searchValue, setSearchValue] = useState();
  const [treelistdata, setTreelistdata] = useState([]);
  const refsData = useRef([]);


  useEffect(() => {
    const asyncTypes = async () => {
      let res = await treelist({ deptName: searchValue })
      res.code === requestCode.successCode && setTreelistdata(res.data);
    }
    asyncTypes();
  }, [searchValue])

  const onSearch = value => {
    setSearchValue(value)
  }
  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys[0], info);
    // let selectedid = selectedKeys[0]
    reviceProps.setUserManageData(selectedKeys[0]);
  };
  const { TreeNode } = Tree;

  const getTreeNode = (treelistdata) => {
    if (treelistdata && treelistdata.length > 0) {
      return treelistdata.map((item) => {
        if (item.children && item.children.length) {
          return (
            <TreeNode key={item.deptId} title={item.deptName}>
              {getTreeNode(item.children)}
            </TreeNode>
          );
        }
        return (
          <TreeNode
            key={item.deptId}
            title={item.deptName}
          // switcherIcon={}
          />
        );
      });
    }
    // return [];
  };
  const tree = useMemo(() => {
    return <>
      <Tree
        style={{ width: '100%', marginTop: 50 }}
        showLine
        switcherIcon={<DownOutlined />}
        // defaultExpandedKeys={['0-0-0']}
        onSelect={onSelect}
        autoExpandParent={true}
        defaultExpandAll={true}
      // treeData={treelistdata}
      >
        {getTreeNode(treelistdata)}
      </Tree>
    </>;
  }, [treelistdata])
  // console.log(userManageMenu(treelistdata), '111')
  return (
    <div style={{ border: '1px solid #f0f0f0',padding: '10px',height:'720px'}}>
      <Search placeholder="输入部门名称搜索" onSearch={onSearch} enterButton style={{ paddingTop: 20 }} />

      {treelistdata.length ? tree : RouterLoading}
    </div>
  )
})

export default Department

3.UserList组件中的写法

import React, { memo, useEffect, useCallback, useContext, useState } from 'react'
import { LayoutTableComponent } from "@/components/layoutTable";
import SaleSearch from "@/components/searchCompent";
import { useSetState, useDel, usePagaTion } from '@/hooks'
import AddUser from "@/container/setModule/addUser";
import { SAGA_SYSUSER_LIST } from '@/redux/constants/sagaType'
import { createSelector } from 'reselect';
import { useSelector, useDispatch } from "react-redux";
import OPtionCompent from '@/components/optionCompent'
import { sysuserdel, sysuserresetPwd } from "@/api/set";
import { Switch, notification } from 'antd';
import { asstate } from "@/assets/js/staticData";
import { confirm, quenue } from '@/utils/function'
import { requestCode } from '@/utils/varbile';
import { userManageContext } from '@/pages/set/userManage'

const UserList = memo(function UserList(props) {
  const reviceProps = useContext(userManageContext);
  const [editData, setEditData] = useSetState({ visible: false, datailData: {} });
  const [searchValue, setSearchValue] = useSetState({});
  const { forceUpdate, pagaTion, changePgVal } = usePagaTion();

  const selectNumOfDoneTodos = createSelector(
    [(state) => state.set],
    (set) => [set.sysuserlist]
  );
  const [sysuserlist] = useSelector(selectNumOfDoneTodos);

  const initFetch = useCallback((searchValue) => {
    const searchsVal = Object.assign({}, searchValue, { start: searchValue.createTime && searchValue ? searchValue.createTime[0] : null, end: searchValue.createTime ? searchValue.createTime[1] : null, createTime: null })
    dispatch({ type: SAGA_SYSUSER_LIST, payload: { ...pagaTion.current, ...searchsVal } }
    )
  }, [dispatch, pagaTion.current]

  );

  const dispatch = useDispatch();

  useEffect(() => {
    initFetch({ ...searchValue, deptId: reviceProps.userManageData })
  }, [initFetch, searchValue, reviceProps.userManageData])

  const [deletedata] = useDel(sysuserdel, () => initFetch());
  const columns = [
    {
      key: 'id',
      align: 'center',
      title: '序号',
      fixed: 'left',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
    },
    {
      title: '昵称',
      dataIndex: 'nicoName',
      key: 'nicoName',
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      align: 'center',
    },
    {
      title: '电话',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
      align: 'center',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      align: 'center',
    },
    {
      title: '部门/岗位',
      dataIndex: 'deptName',
      key: 'deptName',
      align: 'center',
      render: (text, record) =>
        <>
          <span>{record.deptName}</span> / <span>{record.postName}</span>
        </>
    },
    {
      title: '状态',
      dataIndex: 'isdelete',
      key: 'isdelete',
      align: 'center',
      render: (text, record, index) =>
        <>
          <Switch checkedChildren="激活" unCheckedChildren="禁用" key={text} defaultChecked={!text} disabled={true} />
        </>
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
    },
    {
      width: 200,
      title: '操作',
      dataIndex: 'createTime',
      align: 'center',
      fixed: 'right',
      render: (text, record) => (
        <>
          {
            !record.isdelete ? <OPtionCompent config={
              [
                { title: '编辑', operating: () => handle(2, record) },
                { title: '重置密码', color: 'green', operating: () => resetPwd(record) },
                { title: '删除', color: 'red', operating: () => deletedata({ userId: record.userId, listen: Math.random() * 1000, idKey: 'userId' }) }
              ]
            } /> : null
          }

        </>
      )
    },
  ];
  const datas = {
    btnGrounp: [
      {
        title: '新增',
        onClick: (e) => handle(1),
        iconClass: 'add'
      },
      // {
      //   title: '导出',
      //   onClick: (e) => handle(),
      //   iconClass: 'export',
      //   type: "dashed"
      // },
      // {
      //   title: '删除',
      //   onClick: (e) => handle(),
      //   iconClass: 'delete',
      // }
    ],
    tableProps: {
      id: 'userId',
      columns: columns,
      dataSource: sysuserlist.rows,
      scroll: { x: 1500, y: 400 },
      loading: false,
    },
    pagaTionProps: {
      total: sysuserlist.total || 0,
      current:pagaTion.current.page,
      pageSize:pagaTion.current.size,
      onChanges: (page, size) => [changePgVal(page, size), forceUpdate()],
    },
    receive: () => initFetch(),
  }
  const searchConfig = [
    {
      title: '名称',
      key: 'username',
      type: 'input'
    },
    {
      title: '日期',
      key: 'createTime',
      type: 'timeRangeSelection'
    },
    {
      title: '状态',
      key: 'isdelete',
      type: 'select',
      selectListValue: asstate,
      selectLableName: 'value',
      selectKeyValue: 'label'
    },

  ];
  const handle = (state, datailData = {}) => {
    setEditData({ visible: true, datailData })
  }
  const resetPwd = async (record) => {
    confirm(async () => {
      let res = await sysuserresetPwd({ userId: record.userId })
      if (res.code === requestCode.successCode) {
        notification['success']({
          message: '你重置的默认密码如下',
          description: 'admin123456',
          duration: 8,
        });
      }
    }, '你确定要重置密码吗?');
  }
  return (
    <div style={{ border: '1px solid #f0f0f0', padding: '10px', height: '720px' }}>
      <LayoutTableComponent {...datas}>
        <SaleSearch options={searchConfig} callBack={setSearchValue} />
      </LayoutTableComponent>
      <AddUser {...editData} onCancel={() => setEditData({ visible: false })} sucessCallback={() => initFetch(searchValue)} />
    </div>
  )
})

export default UserList

组件Department向组件UserList传值

引入父组件中的设置

import { userManageContext } from '@/pages/set/userManage'

取参数两个子组件都要写

const reviceProps = useContext(userManageContext);

存值

reviceProps.setUserManageData(selectedKeys[0]);

取值

reviceProps.userManageData

你可能感兴趣的:(react)