首页 > 解决方案 > 使用 typescript jsx 进行配置

问题描述

我在使用打字稿进行配置时遇到问题。这是我在 tsconfig.json 中的以下代码:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": [
    "src"
  ]
}

这是我遇到的错误:

编译失败。

./src/Components/AdvancedSearch/AdvancedSearch.tsx Line 80:21: 'JSX' is not defined no-undef

搜索关键字以了解有关每个错误的更多信息。

导致错误 AdvancedSearch.tsx 的文件:

在 AdvancedSearch 中编辑和更新完整代码

type AdvancedSearchState = {
  containerHeight: number,
  showMore: boolean,
  transitioning: boolean;
};
type Props = {
  show: boolean;
  // selected: [ContractType];
  selected: any;
  onChange: (e: any) => void;
  contracts: ContractType[];
};
class AdvancedSearch extends React.Component<Props, AdvancedSearchState> {
  advancedSearchContainer: React.RefObject<HTMLDivElement>;
  advancedSearchWrapper: React.RefObject<HTMLDivElement>;
  width: number = 3;
  labelStyle = {
    color: "#1e7e34",
    "text-decoration": "underline"
  };
  constructor(props: Props) {
    super(props);
    this.selectItem = this.selectItem.bind(this);
    this.advancedSearchContainer = React.createRef();
    this.advancedSearchWrapper = React.createRef();
    this.resize = this.resize.bind(this);
    this.state = {
      showMore: false,
      containerHeight: 0,
      transitioning: true
    };
  }
  getContainerHeight() {
    let containerHeight = 0;
    if (this.advancedSearchContainer.current) {
      containerHeight = this.advancedSearchContainer.current.clientHeight;
    }
    return containerHeight;
  }
  resize() {
    let containerHeight = this.getContainerHeight();
    if (this.state.containerHeight !== containerHeight) {
      this.setState({ containerHeight: containerHeight });
    }
  }
  componentDidMount() {
    this.setState({ containerHeight: this.getContainerHeight() });
    window.addEventListener("resize", this.resize);
  }
  componentWillUnmount() {
    window.removeEventListener("resize", this.resize);
  }
  componentDidUpdate() {
    console.log(this.state.containerHeight);
    this.resize();
  }
  selectItem(name: string) {
    // let selectedContract = name.currentTarget.name;
    // currently change the selectedContract as just the string
    let selectedContract = name;
    let selected = this.props.selected;
    let inx = this.props.selected.indexOf(selectedContract);
    if (inx > -1) {
      selected.splice(inx, 1);
    } else {
      selected.push(selectedContract);
    }
    let event = {
      target: {
        value: selected,
        name: "contracts"
      }
    };
    this.props.onChange(event);
  }
  chunkArray(array: JSX.Element[], width: number) {
    return array.reduce((acc: any[][], item: any, index: number) => {
      let loc = Math.floor(index / width);
      if (!acc[loc]) {
        acc[loc] = [];
      }
      acc[loc].push(item);
      return acc;
    }, []);
  }

  render() {
    //TODO: Should be passed in and not the list of contracts
    let initialList = this.chunkArray(
      this.props.contracts.map(contractType => {
        return (
          <div className="four columns contract-container">
            <span className="contract-header">
              {contractType.contractTypeName}
            </span>
            <dl className="contract-list">
              {contractType.contracts.map(contract => {
                return (
                  <li className="contract">
                    <MvwCheckbox
                      labelStyle={this.labelStyle}
                      onChange={this.selectItem}
                      checked={this.props.selected.indexOf(contract.name) >= 0}
                      label={contract.name}
                      name={contract.name}
                    />
                  </li>
                );
              })}
            </dl>
          </div>
        );
      }),
      this.width
    );
    let list;
    if (this.state.showMore) {
      list = initialList.map((item: React.ReactNode) => {
        return <div className="row">{item}</div>;
      });
    } else {
      list = [initialList[0]].map(item => {
        return <div className="row">{item}</div>;
      });
    }
    return (
      <div
        className={
          "twelve column advanced-search " + (this.props.show ? "show" : "")
        }
      >
        <div
          className="advanced-search-wrapper"
          ref={this.advancedSearchWrapper}
          style={{ height: this.props.show ? this.state.containerHeight : 0 }}
        >
          <div
            className="advanced-search-content"
            ref={this.advancedSearchContainer}
          >
            <div className="advanced-search-body">
              <div className="advanced-search-title">
                <p>
                  Please select the product(s) you wish to use for your
                  Reservation Search:
                </p>
              </div>
              <div className="advanced-search-list">{list}</div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default AdvancedSearch;

更新并添加了 AdvancedSearch 文件的导入:

import React from "react";
import MvwCheckbox from "../../Generic/MvCheckBox";
import "./AdvancedSearch.css";
import ContractType from "../../Interfaces/AdvanceSearchInterface"

标签: javascriptreactjstypescripteslint

解决方案


no-undef在这种情况下导致 ESLint/TypeScript 兼容性问题。查看具体提到您的问题的常见问题解答。我将在这里引用相关部分:

我们强烈建议您不要no-undef在 TypeScript 项目中使用 lint 规则。它提供的检查已经由 TypeScript 提供,无需配置 - TypeScript 只是在这方面做得更好。

从我们的 v4.0.0 版本开始,这也适用于类型。如果你使用来自第 3 方包的全局类型(即来自@types包的任何东西),那么你必须适当地配置 ESLint 来定义这些全局类型。例如; JSX命名空间 from@types/react是您必须在 ESLint 配置中定义的全局第 3 方类型。

有关定义全局变量的帮助,请参阅此ESLint指南。您需要在其中添加一个globals部分,.eslintrc其中包括JSX

"globals": {
    "JSX": "readonly",
},

您可以通过在您no-undef的定义中完全关闭该项目:rules.eslintrc

"rules": {
    "no-undef": "off"
}

或者,如果您有一个混合的 TS/JS 项目,您可以添加一个overrides部分来关闭此针对打字稿文件的规则:

"overrides": [
    {
        "files": ["*.ts", "*.tsx"],
        "rules": {
            "no-undef": "off"
        }
    }
]

推荐阅读