在TypeScript中使用React Blueprint组件遇TS2607错误,求排查问题
解决React+Blueprint组件在TSX中出现的
JSX element class does not support attributes错误 嘿,这个TS2607错误我之前也碰到过,其实问题出在TypeScript对React组件类的类型校验逻辑上。先看看你的代码和报错:
文件名为App.tsx,代码如下:
import * as React from 'react'; import { Button } from "@blueprintjs/core" class App extends React.Component { render() { return <Button intent="success" text="button content" /> } } export default App;运行时报错:
JSX element class does not support attributes because it does not have a 'props' property.ts(2607)
错误原因
在TypeScript里,React.Component是一个泛型类,它的定义是Component<P = {}, S = {}, SS = any>——其中P代表组件的props类型,S是state类型。当你直接写extends React.Component而不指定泛型参数时,TypeScript会默认把props类型推断为unknown,而unknown类型无法支持JSX属性的传递,所以就会抛出这个错误。
修复方案
有几种简单的方式可以解决这个问题,你可以根据自己的需求选择:
方案1:指定空props类型
如果你的组件暂时不需要自定义props,直接给React.Component传入空对象类型{}作为泛型参数即可:
import * as React from 'react'; import { Button } from "@blueprintjs/core" // 明确指定props类型为空对象,state如果不需要可以省略 class App extends React.Component<{}> { render() { return <Button intent="success" text="button content" /> } } export default App;
方案2:提前定义props接口
如果后续你的组件需要接收自定义props,可以先定义一个props接口,再传入泛型参数:
import * as React from 'react'; import { Button } from "@blueprintjs/core" // 定义组件的props类型 interface AppProps { // 比如这里可以加自定义属性:pageTitle: string; } class App extends React.Component<AppProps> { render() { return <Button intent="success" text="button content" /> } } export default App;
方案3:改用函数式组件(推荐)
如果你的项目使用React 16.8+,更推荐用函数式组件的写法,TypeScript对函数式组件的类型推断更友好,代码也更简洁:
import * as React from 'react'; import { Button } from "@blueprintjs/core" // 使用React.FC(FunctionComponent)类型 const App: React.FC = () => { return <Button intent="success" text="button content" /> } export default App;
内容的提问来源于stack exchange,提问作者Geeky
相关产品推荐
相关产品推荐

