React +typescript+antd框架出错的相关问题与解决

搭建React和typescript框架问题汇总与解决方案

编译问题1,是有未使用的变量
 @typescript-eslint/no-unused-vars

解决办法,可创建.eslint文件。需要全局安装eslint,不然eslint init命令会报找不eslint错误。

// 全局安装
npm install eslint -g
//在项目目录安装eslint包
npm install eslint --save-dev
// 生成.eslintrc.js文件
eslint init
//配置如下:
// .eslintrc.js
module.exports = {
  "rules": {
    "no-unused-vars": "off", //禁用
    "@typescript-eslint/no-unused-vars": ["off"], //禁用
  },
  //...
};
编译问题2
Unexpected any. Specify a different type  @typescript-eslint/no-explicit-any

解决办法,在.eslintrc.js文件配置如下:

module.exports = {
  "rules": {
    "@typescript-eslint/no-explicit-any": ["off"] //禁用
  },
  //...
};
编译问题3
 Unnecessary semicolon  @typescript-eslint/no-extra-semi

解决办法,在.eslintrc.js文件配置如下:

module.exports = {
  "rules": {
    "semi": 0, // eslint 不检查分号
  },
  //...
};
编译问题4
 Forbidden non-null assertion  @typescript-eslint/no-non-null-assertion

解决办法,在.eslintrc.js文件配置如下:

module.exports = {
  "rules": {
    "@typescript-eslint/no-non-null-assertion": ["off"] //禁用
  },
  //...
};
require引入问题
'require' is not defined.eslintno-undef

需要修改下 eslint 的配置,一般 eslint 配置文件为 .eslintrc.js

// .eslintrc.js
module.exports = {
  env: {
    node: true // 只需将该项设置为 true 即可
  },
  //...
};
react 取消每次运行项目默认打开浏览器

找到package.json 文件,修改 node scripts/start.js 为 set BROWSER=none&&node scripts/start.js,不要留空格,这样每次启动项目就不会打开浏览器了

"scripts": {
    "start": "set BROWSER=none&&node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
create-react-app搭建的react项目中配置alias

先运行脚本eject npm run eject | yarn run eject
找到项目中paths.js文件

module.exports = {
...
  swSrc: resolveModule(resolveApp, 'src/service-worker'),
  appSrcComponents: resolveApp("src/components"), // 自己加的路径配置
  publicUrlOrPath,
}

在paths.js同目录下找到webpack.config.js,并修改里面的resolve.alias

alias: {
        // Support React Native Web
        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
        'react-native': 'react-native-web',
        // Allows for better profiling with ReactDevTools
        ...(isEnvProductionProfile && {
          'react-dom$': 'react-dom/profiling',
          'scheduler/tracing': 'scheduler/tracing-profiling',
        }),
        ...(modules.webpackAliases || {}),
        // 加自己的配置
        '@':paths.appSrc,
        '@components': paths.appSrcComponents,
      },

使用如下:

import '@/assets/icons'
增加对less的支持的配置

安装less插件

yarn add less less-loader --dev

在webpack.config.js中配置如下:

// 添加配置
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

//第一段(test: /(\.less)$/,...)配置必须放前面(一定要是前面,后面就不起作用了)加上如下代码:
module: {
      strictExportPresence: true,
      rules: [
      	//...
			{
              test: /(\.less)$/,
              use: [
                'style-loader',
                'css-loader',
                {
                  loader: 'less-loader',
                  options: {
                    lessOptions: {
                      javascriptEnabled: true,
                    },
                  },
                },
              ],
            },
            {
              test: lessRegex,
              exclude: lessModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                modules: true,
                sourceMap: isEnvProduction && shouldUseSourceMap
              },
                "less-loader"
              ),
              sideEffects: true
            },
            {
              test: lessModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
                modules: true,
                getLocalIdent: getCSSModuleLocalIdent
              },
                "less-loader"
              )
            },
            //...
       ]
    }

因为 webpack 4.X版本以后把use封装了成了方法,getStyleLoaders,如果用了这个方法,就不能在写options了,会有冲突,所以要单独配置一下less-loader

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个基于React+TypeScript+Ant Design+Umi的可搜索树形控件的代码示例: ``` import React, { useState, useEffect } from 'react'; import { Tree, Input } from 'antd'; import { SearchOutlined } from '@ant-design/icons'; import { TreeProps } from 'antd/lib/tree'; import { DataNode } from 'rc-tree/lib/interface'; import { debounce } from 'lodash'; interface SearchTreeProps extends TreeProps { data: DataNode[]; } const SearchTree: React.FC<SearchTreeProps> = ({ data, ...props }) => { const [expandedKeys, setExpandedKeys] = useState<string[]>([]); const [searchValue, setSearchValue] = useState<string>(''); const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true); const [treeData, setTreeData] = useState<DataNode[]>(data); const handleSearch = debounce((value: string) => { const expandedKeys = getExpandedKeysBySearchValue(value, data); setExpandedKeys(expandedKeys); setSearchValue(value); setAutoExpandParent(true); }, 300); const handleExpand = (expandedKeys: string[]) => { setExpandedKeys(expandedKeys); setAutoExpandParent(false); }; const handleFilterTreeNode = (node: DataNode) => { if (node.title && node.title.toLowerCase().includes(searchValue.toLowerCase())) { return true; } return false; }; const handleRenderTreeNode = (node: DataNode) => { if (node.children) { return ( <Tree.TreeNode key={node.key} title={node.title}> {node.children.filter(handleFilterTreeNode).map(handleRenderTreeNode)} </Tree.TreeNode> ); } return node.title; }; useEffect(() => { const filteredTreeData = data.filter(handleFilterTreeNode).map(handleRenderTreeNode); setTreeData(filteredTreeData); }, [searchValue, data]); return ( <div> <Input placeholder="Search" prefix={<SearchOutlined />} onChange={(e) => handleSearch(e.target.value)} style={{ marginBottom: 8 }} /> <Tree {...props} expandedKeys={expandedKeys} autoExpandParent={autoExpandParent} onExpand={handleExpand} > {treeData} </Tree> </div> ); }; const getExpandedKeysBySearchValue = (searchValue: string, data: DataNode[]): string[] => { const expandedKeys: string[] = []; const loop = (data: DataNode[]) => { data.forEach((item) => { if (item.title.toLowerCase().includes(searchValue.toLowerCase())) { expandedKeys.push(item.key.toString()); } if (item.children) { loop(item.children); } }); }; loop(data); return expandedKeys; }; export default SearchTree; ``` 这个组件接收一个data属性,用于渲染树形控件。在组件内部,我们使用了useState和useEffect来处理组件状态和生命周期,使用了Ant Design的Tree和Input组件来实现树形控件和搜索框。我们使用了lodash库里的debounce函数来限制搜索框的搜索频率。 在handleSearch函数中,我们根据用户输入的内容,获取符合条件的节点的父节点的key,并将它们设置为展开状态。我们使用useState来保存展开状态、搜索值和是否自动展开父节点的状态。 在handleExpand函数中,我们处理了展开状态的变化。 在handleFilterTreeNode函数中,我们判断节点是否符合搜索条件。 在handleRenderTreeNode函数中,我们渲染符合搜索条件的节点。 在useEffect中,我们根据搜索值过滤数据,并重新渲染树形控件。 最后,我们将搜索框和树形控件渲染到页面上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值