将JSX转换为反应组件



假设我有一个称为'myComponent'的组件,我想将其存储在类型的'myComponts'中,但使用JSX元素来初始化它,例如:

let comp: MyComponent = <MyComponent somePropInit={3} />

以上代码会产生错误:

'属性'componentDidmount'在类型'元素'中缺少

实际组件我正在使用:

export class PlayCard extends React.Component<AllCardProps, {}> {
    addToDeck(){...}

我正在尝试存储它(我尝试了许多不同的事情,包括使用TypeOf,card.playcard,PlayCard等):

import * as Card from './PlayCard'
...
let c: Card.PlayCard = <PlayCard Id={32} />

^如果我尝试以上我会有错误

'属性'addTodeck'在类型'组件&lt; ...>'

中缺少

如果我删除addTodeck,则错误将移至下一个函数向下移动。看起来存在的任何功能都以某种方式将其扔掉了?

我将如何完成此操作?

反应组件的生命周期方法是可选的。

以下是接口的示例:

interface ComponentLifecycle < P, S > {
    /**
     * Called immediately before mounting occurs, and before `Component#render`.
     * Avoid introducing any side-effects or subscriptions in this method.
     */
    componentWillMount ? () : void;
    /**
     * Called immediately after a compoment is mounted. Setting state here will trigger re-rendering.
     */
    componentDidMount ? () : void;

因此,错误不在React/Typescript中。您可能使用了引起问题的接口。

参考:

  • @types/react/index.d.ts:请参阅第355。

最新更新