简体   繁体   中英

Convert jsx to react component?

Suppose I have a component called 'MyComponent', and I want to store it in a variable of type 'MyComponent' in typescript but use the JSX element to initialise it, something like:

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

The above code generates errors like:

'property 'componentDidMount' is missing in type 'Element'

Actual component I'm using:

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

how I'm trying to store it (I've tried many different things including using typeof, Card.PlayCard, PlayCard , etc):

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

^ if I try the above I get an error

'Property 'addToDeck' is missing in type 'Component<...>'

If I delete addToDeck the error moves on to the next function down. Looks like any function which exists throws it off somehow?

How would I accomplish this?

Life-cycle methods for a React component are optional values.

Following is the sample for interface:

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;

So the error is not in React/typescript. You might have used an interface that is causing issue.

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM