1

我正在自学在 React Native 中使用 TypeScript 构建应用程序。作为 Swift 开发人员,JS 和 TS 需要一点时间来适应。

我注意到的一件事是,似乎不可能在 Render 方法的另一个 tsx 文件中使用我在 tsx 文件中编写的组件。

//SomeComponent.tsx

export default class SomeComponent extends Component {
    //all my logic
}

//OtherComponent.tsx
export default class ScoreTable extends Component {
    //logic
    render() {

      <SomeComponent style={{flex: 1}}></SomeComponent>
    }
}

这会给我以下错误:

Type '{ style: { flex: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<SomeComponent> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

我可以通过简单地将我的 tsx SomeComponent 转换为 .js 组件来解决这个问题,但我真的很喜欢 tsx 语法。所以我的问题是为什么我不能在其他 tsx 组件中使用 .tsx 组件?还是有其他方法可以做到这一点?

4

2 回答 2

1

You need to define style as a prop that your SomeComponent accepts:

import React, { Component, CSSProperties } from "react";

interface Props {
  style: CSSProperties;
}

export default class SomeComponent extends Component<Props> {
于 2019-05-14T21:27:55.880 回答
1

I agree this error is confusing.

What's the problem?

Essentially, this is due to not specifying the type for the Props of SomeComponent correctly, leading TypeScript to assume the bare minimum type definition, which does not include a style property.

How do I fix it?

Add an interface for the props you expect to be accepted by SomeComponent, in much the same way as you might have previously done using PropTypes.

//SomeComponent.tsx

interface SomeComponentProps {
    style: React.CSSProperties;
}

export default class SomeComponent extends Component<SomeComponentProps> {
    //all my logic
}

How did you figure that out?

There are a few clues. The first is the Type '{ style: { flex: number; }; }' part, which looks an awful lot like the attributes (a.k.a. props) you specify when using SomeComponent in OtherComponent.tsx. So it probably has something to do with props for SomeComponent.

The next part of the error says is not assignable to type, confirming that TypeScript thinks the type of the props doesn't match what it knows about SomeComponent.

The final part of the error is the most confusing, where it lists the type 'IntrinsicAttributes & IntrinsicClassAttributes<SomeComponent> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Searching for IntrinsicAttributes in my React code allowed me to see that it was indeed to do with the base type of the attributes expected by a component (I found it in node_modules/@types/react/index.d.ts, the type definitions for react).

Combining all of these clues with the prior knowledge of how to strongly type the props and state of custom react components in TypeScript using the two optional generic type params to React.Component lead me to the final solution.

Hopefully you now feel more empowered to decipher similarly confusing error messages in future.

于 2019-05-14T21:28:00.413 回答