首页 > 其他分享 >react 内容

react 内容

时间:2023-07-13 09:34:29浏览次数:37  
标签:src const element react 内容 path import

1、初始安装react+ts

 npx create-react-app my-app   

npx create-react-app react-ts  --template typescript  安装为ts

2、安装好react 后面加上ts

   2.1 tsc --init  生产tsconfig.js



{
  "compilerOptions": {
    "target": "es5" /**指定ECMAScript目标版本**/,
    "module": "commonjs" /**指定生成哪个模块系统代码**/,
    "allowJs": true /**允许编译js文件**/,
    "jsx": "preserve" /**支持JSX**/,
    "outDir": "build" /**编译输出目录**/,
    "strict": true /**启用所有严格类型检查选项**/,
    "noImplicitAny": false /**在表达式和声明上有隐含的any类型时报错**/,
    "skipLibCheck": true /**忽略所有的声明文件的类型检查**/,
    "forceConsistentCasingInFileNames": true /**禁止对同一个文件的不一致的引用**/,
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@assets/*": ["src/assets/*"],
      "@components/*": ["src/components/*"],
      "@pages/*": ["src/pages/*"],
      "@utils/*": ["src/utils/*"],
      "@store/*": ["src/store/*"]
    }
  },
  "include": ["src"] /**指定编译目录**/
}



 

  2.2 引入ts   yarn add typescript   yarn add @types/react @types/react-dom

  2.3 react 里面的文件.js  需要修改为.tsx  包含jsx的都需要改为tsx

3、react 里面的文件.js  需要修改为.tsx

4、安装mobx

yarn add mobx  mobx-react-lite

---React Developer Tools安装

---1 下载包 https://www.crx4chrome.com/crx/3068/  下载crx包

---2 将报的后缀名修改为rar或者zip

---3 解压完成后如下

 ---4打包完成后在chrome加载已解压的文件 

----5加载的文件夹不能删除 删除了插件就找不到了   可以放在一个地方

5、类型断言   

JSON.parse(getUserInfo() as string)   用于ts警告报错 6、token持久化配置  存储到localstorage utils/userInfo.js
//封装userinfo 存到localstorage
const Key = "userInfo"

//set
const setUserInfo = (userInfo)=> {
    return window.localStorage.setItem(Key, userInfo)
}

// get
const getUserInfo = ():string|null=> {
    return window.localStorage.getItem(Key)
}

//remove
const removeUserInfo = ()=> {
    return window.localStorage.removeItem(Key)
}

export {setUserInfo, getUserInfo, removeUserInfo}

保存的时候

let userInfo = {
      token: resp.data.token,
      sessionId: resp.sessionId,
      username: enterpriseAccount,
      relateEnterpriseName: resp.userInfo.enterpriseName,
      relateEnterpriseId: resp.userInfo.id,
      isSuperAdmin: resp.userInfo.isSuperAdmin,
    };
setUserInfo(JSON.stringify(userInfo));

7、组件鉴权  没有token信息就跳转到login

AuthComponent.tsx

//判断用户信息token是否存在
//存在直接渲染
//不存在直接跳转
//AuthComponent 里面加入需要鉴权的组件
import { getUserInfo } from "@/utils/index"
import { Navigate } from "react-router-dom"
function AuthComponent({ children }) {
    const userInfo = JSON.parse(getUserInfo() as string);
    let token = userInfo ? userInfo.token : '';
    if (token !=="") {
        return <>{children}</>
    } else {
        //跳转到登录页
        return <Navigate to={"/login"} />
    }
}

export { AuthComponent }

使用

/*路有需要鉴权的地方使用*/
<Route path="/" element={
            <AuthComponent><Layout /></AuthComponent>
}></Route>

8、ts 设置router index 跳转首页

 <Route index element={
              <AuthComponent><Home /></AuthComponent>
            }></Route>

9、错误信息 

Do you need to change your target library? Try changing the 'lib' compiler option to 'es2021' or later.

 "compilerOptions": {
    "target": "es5" /**指定ECMAScript目标版本**/,
    "module": "commonjs" /**指定生成哪个模块系统代码**/,
    "allowJs": true /**允许编译js文件**/,
    "jsx": "preserve" /**支持JSX**/,
    "outDir": "build" /**编译输出目录**/,
    "strict": true /**启用所有严格类型检查选项**/,
    "noImplicitAny": false /**在表达式和声明上有隐含的any类型时报错**/,
    "skipLibCheck": true /**忽略所有的声明文件的类型检查**/,
    "forceConsistentCasingInFileNames": true /**禁止对同一个文件的不一致的引用**/,
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@assets/*": ["src/assets/*"],
      "@components/*": ["src/components/*"],
      "@pages/*": ["src/pages/*"],
      "@utils/*": ["src/utils/*"],
      "@store/*": ["src/store/*"]
    }
  },
"lib": [ "dom", "es5", "es2015.promise" ,"es2015", "es2017"],


 10、antd menu

菜单点击跳转

const navigate = useNavigate();
//跳转
navigate(key);

菜单点击高亮当前菜单

const [current, setCurrent] = React.useState("/");
//高亮当前
setCurrent(key);
<Menu
   mode="inline"
   defaultSelectedKeys={['/']}
   selectedKeys={[current]}
   className="layout-menu"
   items={MenuList}
    onClick={menuClickHandler}
/>
                  

路由刷新高亮菜单

const location = useLocation();
// 获取当前路由
setCurrent(location.pathname)

11、userEffect [] 调用了两次

去掉严格模式   

  // <React.StrictMode>
    <App />
  // </React.StrictMode>

12、配置多环境变量  

yarn add dotenv-cli 新建env文件  .env  & .env.production
#REACT_APP开头
REACT_APP_URL = ''
REACT_APP_URL_initialize = ''
REACT_APP_ENV=production
package.json 
 "start": "craco start",
 "production": "dotenv -e .env.production craco start",
 "build": "dotenv -e .env.production craco build",

获取参数

const base_obj = {
  base: process.env.REACT_APP_URL,
  initialize: process.env.REACT_APP_URL_initialize,
};

13、外部配置路由跳转

   1.安装history  yarn add history

  2.创建history.ts

import { createBrowserHistory } from 'history'
const browserHistory  = createBrowserHistory()
export default browserHistory 

  3.创建自定义路由文件组件CutstomBrowserRouter.tsx

import * as React from "react";

import { Router } from "react-router-dom";
import browserHistory from "@/utils/history";


export default function CustomBrowserRouter({ basename="", children, window="" }) {
  let historyRef = React.useRef();
  if (historyRef.current == null) {
    //@ts-ignore
    historyRef.current = browserHistory;
  }

  let history:any = historyRef.current;
  let [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      basename={basename}
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
}

  4.index.tsx使用

import CustomBrowserRouter from "@/components/CutstomBrowserRouter";
<CustomBrowserRouter>
    <App />
  </CustomBrowserRouter>

把原来的BrowserRouter替换为CustomBrowserRouter 

14、类型“JSX.IntrinsicElements”上不存在属性“children”。

//Children  需要大写
function BaseSeacrh({ children }) { return <div className="baseSeacrh"> {<children/>} </div> }

15、路由表配置

router/index.tsx
/* eslint-disable import/no-anonymous-default-export */
import * as React from "react";
import { lazy, Suspense, ReactNode, ComponentType, LazyExoticComponent } from "react";
import NotFound from "@/pages/NotFound";
import { AuthComponent } from '@/components/AuthComponent'

interface IRoute {
    path: string,
    element: ReactNode
    children?: IRoute[]
}
function lazyLoad(path: string) {
    const Comp: LazyExoticComponent<ComponentType<any>> = lazy(() => import("@/pages/" + path));
    return (
        <Suspense fallback={<div>加载中……</div>}>
            <Comp />
        </Suspense>
    );
}

const Routers: IRoute[] = [
    {
        path: "/login",
        element: lazyLoad("Login"),
    },
    {
        path: "/",
        element: <AuthComponent>{lazyLoad("LayoutView")}</AuthComponent>,
        children: [
            {
                path: "home",
                element: lazyLoad("Home"),
            },
            {
                path: "menu",
                element: lazyLoad("Menu"),
            },
            {
                path: "role",
                element: lazyLoad("Role"),
            },
            {
                path: "user",
                element: lazyLoad("User"),
            },
            {
                path: "dict",
                element: lazyLoad("Dict"),
            },
            {
                path: "logs",
                element: lazyLoad("Logs"),
            },
            {
                path: "module",
                element: lazyLoad("Module"),
            },
        ],
    },
    {
        path: "*",
        element: <NotFound />,
    },
];
export default Routers

使用

index.js / index.jsx

import { BrowserRouter } from 'react-router-dom'; 
 <BrowserRouter>
    <App />
    </BrowserRouter>

app.js/app.tsx

import { useRoutes } from "react-router-dom";
import "./App.css";
import routes from "@/router"
function App() {
  const element = useRoutes(routes);
  return (
    // <BrowserRouter>
      <div className="App">
        {/* <Routes> */}
          {/* 鉴权 */}
          {/* <Route path="/" element={
            <AuthComponent><LayoutView /></AuthComponent>
          }>
            <Route index element={
              <AuthComponent><Home /></AuthComponent>
            }></Route>
            <Route path="/menu" element={
              <AuthComponent><Menu /></AuthComponent>
            }></Route>
            <Route path="/role" element={
              <AuthComponent><Role /></AuthComponent>
            }></Route>
            <Route path="/user" element={
              <AuthComponent><User /></AuthComponent>
            }></Route>
             <Route path="/dict" element={
              <AuthComponent><Dict /></AuthComponent>
            }></Route>
            <Route path="/logs" element={
              <AuthComponent><Logs /></AuthComponent>
            }></Route>
            <Route path="/module" element={
              <AuthComponent><Module /></AuthComponent>
            }></Route>
          </Route>
          <Route path="/login" element={<Login />}></Route>
        </Routes> */}
        {element}
      </div>
    // </BrowserRouter>
  );
}

export default App;

16、and table增加序号

{
      title: "序号",
      width: 70,
      render: (text, record, index) => `${index + 1}`,
    },

 17、吊用组件函数useRef ref  forwardRef useImperativeHandle 

const RoleFormComRef = useRef<any>(null)  <RoleForm record={record} ref={RoleFormComRef} /> 子组件 需要弹出的方法 function RoleForm({ record }, ref) { useImperativeHandle(ref,         () => ({             getTableList,             setPage })) } export default   forwardRef(RoleForm ) 父组件调用 TableRef?.current?.getTableList()  

标签:src,const,element,react,内容,path,import
From: https://www.cnblogs.com/shuangzikun/p/17471923.html

相关文章

  • c# 读取json字符串节点内容
    c#读取json字符串节点内容stringjsonstr="{\"voiceprompt_callback\":{\"result\":\"1\",\"accept_time\":\"0\"}}";varty=JsonConvert.DeserializeObject(jsonstr);Newtonsoft.Json.Linq.JOb......
  • AI_Pytorch—内容回顾
    pytorch基本结构与组件-基本流程与步骤-基本方法和应用组件PyTorch都是用C++和CUDA编写的modulesandclassestorch.nn, torch.optim, Dataset,andDataLoader学、练、训、赛、研、用device=torch.device("cuda:0"iftorch.cuda.is_available()else......
  • React中编写操作树形数据的自定义Hook
    什么是Hookhook即为钩子,是一种特殊的函数,它可以让你在函数式组件中使用一些react特性,目前在react中常用的hook有以下几类useState:用于在函数组件中定义和使用状态(state)。useEffect:用于在函数组件中处理副作用,也可以模拟react生命周期useContext:用于在函......
  • shallowReactive 与 shallowRef
    shallowReactive:只处理对象最外层属性的响应式(浅响应式)。shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理。什么时候使用?如果有一个对象数据,结构比较深,但变化时只是外层属性变化===>shallowReactive。如果有一个对象数据,后续功能不会修改该对......
  • 解除网站内容无法复制
    有些网站在没有登录时无法复制其中的关键内容。之前网上有方法说输入命令后可以复制,貌似现在没有用了。解禁办法:......
  • DevTools 无法加载源映射: 无法加载httplocalhost8081staticscssbootstrap.min.css.map
    DevTools无法加载源映射:无法加载http://localhost:8081/statics/css/bootstrap.min.css.map的内容:HTTP错误:状态代码404,net::ERR_HTTP_RESPONSE_CODE_FAILURE 解决办法:找到bootstrap.min.css,删除最后一行注释 注意:如果是css报错就删除:/*#sourceMappingURL=bootst......
  • 光伏三相并网仿真 模型内容: 1.光伏+MPPT控制+两级式并网逆变器
    光伏三相并网仿真模型内容:1.光伏+MPPT控制+两级式并网逆变器(boost+三相桥式逆变)2.坐标变换+锁相环+dq功率控制+解耦控制+电流内环电压外环控制+spwm调制3.LCL滤波仿真结果:1.逆变输出与三项380V电网同频同相2.直流母线电压800V稳定3.d轴电压稳定311V;q轴电压稳定为0V,有功功率高效输......
  • 前端框架及项目面试-聚焦Vue、React、Webpack
    第1章课程导学介绍课程制作的背景和课程主要内容。第2章课程介绍先出几道面试真题,引导思考。带着问题来继续学习,效果更好。第3章Vue使用Vue是前端面试必考内容,首先要保证自己要会使用Vue。本章讲解Vue基本使用、组件使用、高级特性和VuexVue-router,这些部分的知识点和......
  • React18+Next.js13+TS,B端+C端完整业务+技术双闭环(20章)
    最新React技术栈,实战复杂低代码项目-仿问卷星第1章开期准备试看3节|20分钟介绍课程内容,学习建议和注意事项。演示课程项目,让学员有一个整体的认识。第2章【入门】什么是ReactReact引领了现代前端开发的变革8节|50分钟介绍React的历史、背景和每次版本更新。介绍R......
  • 学习jQuery核心内容这一篇就够了
    jQuery1.介绍jQuery是JavaScript的工具库,对原生JavaScript中的DOM操作、事件处理、数据处理等进行封装,提供更便捷的方法。让我们用更少的代码完成我们的js操作类似于python当中的模块jQuery有很多个版本.不一定越新越好.可能有的时候用到的都是旧版本的代码,这时候可以不......