Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

reactjs - Typescript Utils class return React Component

I am doing a typescript React project and am attempting writing some utility classes. I am having issues returning a React component this way though and not sure what would I should be doing/what is best practice. I am getting the "refers to a value, but is being used as a type here." error unless I use a tsx file, in which case it can't be properly imported. Also worth noting throwing a @ts-ignore alleviates that error but then errors as "Unterminated regular expression literal"

Edit: this is error with <SomeIcon /> etc.

Here is my BoxUtils.ts

export abstract class BoxUtils {
    public static getIconForStatus(box: BoxModel): Icon | null {
        switch(box.status) {
            case 'StatusOne':
                return <SomeIcon />;
            case 'StatusTwo':
                return <SomeOtherIcon />;
            case 'StatusThree':
                return <YetAnotherIcon />;
            default:
                return null;
        }
    }
}

And this is a fragment of where I would use the util: <div>{BoxUtils.getIconForStatus(row)}</div>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The syntax you've included in the following lines are JSX syntax, meaning that they contain ES6 components that aren't build into the interpreter of the Typescript language.

return <SomeIcon />;
return <SomeOtherIcon />;
return <YetAnotherIcon />;

However you can include these syntax capabilities by marking the file as .tsx rather than .ts. If you were only including typescript functions or types, you could use just the .ts file extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...