标签: tsx

使用TypeScript在React组件中的默认属性值

我无法弄清楚如何使用Typescript为我的组件设置默认属性值.

这是源代码:

class PageState
{
}

export class PageProps
{
    foo: string = "bar";
}

export class PageComponent extends React.Component<PageProps, PageState>
{
    public render(): JSX.Element
    {
        return (
            <span>Hello, world</span>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用这样的组件时:

ReactDOM.render(<PageComponent />, document.getElementById("page"));
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,说财产foo缺失.我想使用默认值.我也尝试static defaultProps = ...在组件内部使用,但它没有像我怀疑的那样有效.

src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
Run Code Online (Sandbox Code Playgroud)

我如何使用默认属性值?我公司使用的许多JS组件都依赖于它们而不使用它们不是一种选择.

typescript reactjs tsx

123
推荐指数
7
解决办法
7万
查看次数

JSX 元素类不支持属性,因为它没有“props”属性。ts(2607)

当我使用react-easy-crop库中的“Cropper”时出现此错误,我尝试了在论坛上找到的一些方法,例如添加@types/react、从“react”导入*作为React,但似乎没有任何效果工作。

这是给我带来麻烦的代码:

import * as React from "react";
import Cropper from "react-easy-crop";

export default function CropperPage({action , valuePro}: any) {
   return (
     <Cropper //  <-- This is giving me the error
        cropShape= "round"
        disableAutomaticStylesInjection="true"
        image={image}
        crop={crop}
        zoom={zoom}
        aspect={1}
        onCropChange={setCrop}
        onZoomChange={setZoom}
        onCropComplete={onCropComplete}
    />
   );
}
Run Code Online (Sandbox Code Playgroud)

整个错误信息是:

Blockquote JSX 元素类不支持属性,因为它没有“props”属性。ts(2607)“Cropper”不能用作 JSX 组件。其实例类型“Cropper”不是有效的 JSX 元素。类型“Cropper”缺少类型“ElementClass”中的以下属性:context、setState、forceUpdate、props、refsts(2786)(别名)class Cropper import Cropper

html javascript jsx reactjs tsx

49
推荐指数
2
解决办法
6万
查看次数

TS2786“组件”不能用作 JSX 组件

我有一个无法编译的 React Typescript 应用程序。许多组件都有一个 render 方法,其类型为返回React.ReactNodeReact.ReactElement。编译时,会报很多类似如下的错误:

TS2786: 'MessagesWidget' cannot be used as a JSX component.
 Its instance type 'MessagesWidget' is not a valid JSX element.
 The types returned by 'render()' are incompatible between these types.
 Type 'React.ReactNode' is not assignable to type 'import("/home/node/app/node_modules/@types/react-calendar/node_modules/@types/react/index").ReactNode'.
Run Code Online (Sandbox Code Playgroud)

为什么编译器期望ReactNode与捆绑的类型相同react-calendar?我确实已@types/react-dom安装为开发依赖项。

其他可能相关的信息:

  1. 该项目直到几天前才进行编译,当编译开始失败时没有代码更改,因此我怀疑包更新触发了此问题(即使这不是根本原因)。当编译开始失败时,在时间窗口中更新的唯一依赖项是@types/react@types/react-dom。然而,将这些软件包回滚到旧版本并没有解决问题。
  2. 将我的组件渲染方法更改为 returnJSX.Element可以消除编译器错误,但应用程序中存在第三方组件,这是不可能的。

typescript reactjs tsx react-dom

44
推荐指数
5
解决办法
8万
查看次数

除非提供'--jsx'标志,否则无法使用JSX

我已经四处寻找解决这个问题的方法了.所有这些都建议添加"jsx": "react"到您的tsconfig.json文件.我做了什么.另外一个是补充"include: []",我也做了.但是,当我尝试编辑.tsx文件时,我仍然收到错误.下面是我的tsconfig文件.

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "allowJs": true,
        "checkJs": false,
        "jsx": "react",
        "outDir": "./build",
        "rootDir": "./lib",
        "removeComments": true,
        "noEmit": true,
        "pretty": true,
        "skipLibCheck": true,
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true
    },
    "include": [
        "./lib/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}
Run Code Online (Sandbox Code Playgroud)

任何的意见都将会有帮助.我正在使用babel 7来编译env,react和typescript预设的所有代码.如果你们需要更多文件来帮助调试这个,请告诉我.

jsx typescript reactjs tsx

36
推荐指数
13
解决办法
2万
查看次数

如何制作一个具有泛型类型的函数式 React 组件?

我正在尝试制作一个 React 组件,它接受一个通用类型参数,该参数将成为其 prop 类型的一部分。

我想要一个看起来像这样的解决方案:

interface TestProps<T> {
  value: T;
  onChange: (newValue: T) => void;
}

const Test: React.FC<TestProps<T>> = (props) => (
  <span>{props.value}</span>
);
Run Code Online (Sandbox Code Playgroud)

我已经看到 TypeScript 2.9 中对此有支持,而我使用的是 4.3.5。

它的用法如下:

const Usage: React.FC = () => (
  <div>
    <Test<Obj>
      value={{ name: 'test' }}
      onChange={(newValue) => {
        console.log(newValue.name);
      }}
    />
  </div>
);
Run Code Online (Sandbox Code Playgroud)

代码沙箱:https://codesandbox.io/s/react-typescript-playground-forked-8hu13?file=/src/ index.tsx

typescript reactjs tsx typescript-generics

33
推荐指数
3
解决办法
3万
查看次数

ReactJS 和 Typescript :指的是一个值,但在此处用作类型(TS2749)

我在 .tsx 文件中使用 Typescript 和 Material-ui 编写 ReactJS 类。在我的自定义组件之一中,我想创建对我在自定义组件中使用的组件之一的引用。

export class MyTextField extends React.Component<MyProps, MyState> {
  private refTextField: React.RefObject<TextField>;
  constructor(props: MyProps) {
    super(props);
    this.refTextField = React.createRef();
  }

  render(): JSX.Element {
    const { id, label, value: defaultValue } = this.props;
    const { value } = this.state;
    const element = (
      <TextField ref={this.refTextField} id={id} label={label} defaultValue={defaultValue} value={value} />
    );

    return element;
  }
}
Run Code Online (Sandbox Code Playgroud)

在编译期间,我在引用的声明中收到错误消息:

'TextField' 指的是一个值,但在这里被用作一种类型。TS2749

我试图将“typeof TextField”放在我的声明中,但在我的渲染中评估 ref 属性时,我有另一条消息:

类型 'RefObject<(props: TextFieldProps) => Element>' 不能分配给类型 '((instance: HTMLDivElement | null) => void) …

validation typescript reactjs material-ui tsx

31
推荐指数
4
解决办法
2万
查看次数

打字稿中的界面状态和道具起反应

我正在开发一个使用打字稿以及反应的项目,对两者都是新手.我的问题是关于打字稿中的界面以及它与道具和状态的关系.究竟发生了什么?除非我声明接口道具和状态,否则我的应用程序根本不会运行,但是我通过反应构造函数使用状态,并且我已经看到所有这些信息将进入"接口MyProps"或"接口MyStates"的示例例

"use strict";

import * as React from 'react'
import NavBar from './components/navbar.tsx'
import Jumbotron from './components/jumbotron.tsx';
import ContentPanel from './components/contentPanel.tsx';
import Footer from './components/footer.tsx';

interface MyProps {}
interface MyState {}
class Root extends React.Component <MyProps, MyState>  {
  constructor(props) {
    super(props);
    this.state = {
      ///some stuff in here

    };
  }
  render() {
    return (
      <div>
        <NavBar/>
        <Jumbotron content={this.state.hero}/>
        <ContentPanel content={this.state.whatIs}/>
        <ContentPanel content={this.state.aboutOne}/>
        <ContentPanel content={this.state.aboutTwo}/>
        <ContentPanel content={this.state.testimonial}/>
        <Footer content={this.state.footer}/>
      </div>
    )
  }
}
export default Root;
Run Code Online (Sandbox Code Playgroud)

(我已经删除了this.state中的内容,只是为了在这里发布).为什么我需要界面?这样做的正确方法是什么,因为我认为我是以jsx方式而不是tsx方式考虑这个问题.

jsx typescript reactjs tsx

28
推荐指数
1
解决办法
4万
查看次数

Prettier 不格式化 .tsx 文件

我在 Visual Studio 代码编辑器中使用 Prettier 扩展已经很长时间了,但最近我正在用 Typescript 写 React。所以我需要配置 Prettier 来格式化 .tsx 文件。

typescript reactjs visual-studio-code tsx prettier

25
推荐指数
5
解决办法
1万
查看次数

React - useRef 与 TypeScript 和功能组件


我试图从父组件调用子组件方法,我试图使用 useRef。将来,SayHi 方法将更新子组件中的钩子状​​态。不幸的是,我有无法处理的错误。

行:ref.current.SayHi();

类型“ForwardRefExoticComponent<{ name: string;”上不存在属性“SayHi” } & RefAttributes<{ SayHi: () => void; }>>'。

行:< Child name="Adam" ref={ref}/>

输入'RefObject void; }>>>' 不能分配给类型 '((instance: { SayHi: () => void; } | null) => void) | RefObject<{ SayHi: () => void; }> | 空| 不明确的'。输入'RefObject void; }>>>' 不能分配给类型 'RefObject<{ SayHi: () => void; }>'。“ForwardRefExoticComponent<{ name: string;”类型中缺少“SayHi”属性 } & RefAttributes<{ SayHi: () => void; }>>' 但在类型 '{ SayHi: () => void; 中是必需的; }'。


完整的 test.tsx 文件:

import React, { useRef, …
Run Code Online (Sandbox Code Playgroud)

ref typescript reactjs tsx react-functional-component

21
推荐指数
1
解决办法
3万
查看次数

如何通过 Typescript 使用 TailwindCSS 的解析配置

我将以下代码导入到我的 .tsx 组件中:

import resolveConfig from 'tailwindcss/resolveConfig';
import tailwindConfig from '../../../tailwind.config.js';

const fullConfig = resolveConfig(tailwindConfig)
Run Code Online (Sandbox Code Playgroud)

如果我随后引用,fullConfig.theme.colors["blue"]["700"]则会收到一条错误消息:

元素隐式具有“any”类型,因为“blue”类型的表达式不能用于索引类型“TailwindThemeColors”。类型“TailwindThemeColors”上不存在属性“蓝色”。

颜色的 Tailwind 类型定义是:

export type TailwindColorValue = string | TailwindColorGroup | TailwindColorFunction;

export interface TailwindValuesColor {
    readonly [key: string]: TailwindColorValue;
}
Run Code Online (Sandbox Code Playgroud)

由于该类型没有明确指出这"blue"是一个值并且它可能是一个对象,所以这就是错误的原因(我认为)。

我遇到的另一个问题是我的 中出现错误tsconfig.json,因为我正在导入 JS 文件。添加并"exclude": ["tailwind.config.js"]不能解决问题。

我很确定这是一个 Typescript 问题,而不是 Tailwind 问题......

我的问题是:

  1. 如何让 Typescript 了解"blue"顺风主题中颜色的属性,以及
  2. 如何阻止导入 JS 配置时出现 tsconfig 错误?

typescript reactjs tsx tailwind-css

21
推荐指数
1
解决办法
2万
查看次数