xccjk / x-blog

学习笔记
18 stars 2 forks source link

react #91

Open xccjk opened 1 year ago

xccjk commented 1 year ago

react tsx 引入 less 文件,警告找不到模块“../index.less xxx,但是可以正常运行

全局ts配置文件typings.d.ts

declare module '*.less' {
  const classes: { [key: string]: string };
  export default classes;
}

使用变量接收less文件

const styles = require('./index.less')
xccjk commented 1 year ago

使用react-dev-inspector,来快速找到页面中组件对应的问题

安装依赖

yarn add react-dev-inspector -D

项目根节点配置(以umi2/umi3做示例)

import React from 'react';
import ProLayout from '@ant-design/pro-layout';
import { Inspector } from 'react-dev-inspector';

const BasicLayout = (props) => {
  return (
    <>
      <ProLayout
        {...props}
      >
        {children}
      </ProLayout>
      {isDev && (
        <Inspector
          keys={['control', 'shift', 'command', 'c']}
          disableLaunchEditor={true}
          onClickElement={({ codeInfo }) => {
            if (!codeInfo?.absolutePath) return;
            const { absolutePath, lineNumber, columnNumber } = codeInfo;
            window.open(`vscode://file/${absolutePath}:${lineNumber}:${columnNumber}`);
          }}
        >
          <div />
        </Inspector>
      )}
    </>
  );
};

export default <BasicLayout />

注意的点:

Inspector组件内部需要放一个空的子元素,不然会报错 issue

使用方式

在页面跑起来项目后,快捷键control + shift + command + c,点击dom元素就可以打开vscode了

npm 地址

xccjk commented 1 year ago

react context怎么在hooks组件中与函数组件中使用

hooks组件

import React, { useContext } from 'react';
import { BaseContext } from '@/store';

const Home = () => {
  const [base] = useContext(BaseContext);

  return ...;
};

export default Home;

函数组件

如果使用了withRouter包裹组件

import React, { PureComponent } from 'react';
import { withRouter } from 'umi';

import { BaseContext } from '@/store';

class Home extends PureComponent {
  ...
}
// 注意contextType要放在export default后面
export default withRouter(Home);
Home.contextType = BaseContext;
import React, { PureComponent } from 'react';

import { BaseContext } from '@/store';

class Home extends PureComponent {
  ...
}

export default Home;
xccjk commented 1 year ago

已打开页面在项目发版时,js文件名访问不到导致的报错

https://www.codemzy.com/blog/fix-chunkloaderror-react