我写了一些代码:
function renderGreeting(Elem: React.Component<any, any>) {
return <span>Hello, <Elem />!</span>;
}
我得到一个错误:
JSX元素类型Elem没有任何构造或调用签名
这是什么意思?
我写了一些代码:
function renderGreeting(Elem: React.Component<any, any>) {
return <span>Hello, <Elem />!</span>;
}
我得到一个错误:
JSX元素类型Elem没有任何构造或调用签名
这是什么意思?
当前回答
import React from 'react';
function MyComponent (
WrappedComponent: React.FunctionComponent | React.ComponentClass
) {
return (
<Wrapper>
<WrappedComponent />
</Wrapper>
);
}
其他回答
在我的例子中,我在类型定义中缺少new。
some-js-component.d。ts文件:
import * as React from "react";
export default class SomeJSXComponent extends React.Component<any, any> {
new (props: any, context?: any)
}
在tsx文件中,我试图导入非类型化组件:
import SomeJSXComponent from 'some-js-component'
const NewComp = ({ asdf }: NewProps) => <SomeJSXComponent withProps={asdf} />
你可以使用
function renderGreeting(props: {Elem: React.Component<any, any>}) {
return <span>Hello, {props.Elem}!</span>;
}
但是,下面的方法有用吗?
function renderGreeting(Elem: React.ComponentType) {
const propsToPass = {one: 1, two: 2};
return <span>Hello, <Elem {...propsToPass} />!</span>;
}
如果你将功能组件作为道具传递给另一个组件,请使用以下命令:
import React from 'react';
type RenderGreetingProps = {
element: React.FunctionComponent<any>
};
function RenderGreeting(props: RenderGreetingProps) {
const {element: Element} = props;
return <span>Hello, <Element />!</span>;
}
当声明React Class组件时,使用React。ComponentClass而不是React。组件,那么它将修复ts错误。
如果你使用的是material-ui,转到组件的类型定义,它是由TypeScript下划线。你很可能会看到这样的东西
export { default } from './ComponentName';
你有两个选项来解决这个错误:
1.在JSX中使用组件时添加.default:
import ComponentName from './ComponentName'
const Component = () => <ComponentName.default />
2.在导入时,将组件重命名为“default”:
import { default as ComponentName } from './ComponentName'
const Component = () => <ComponentName />
这样就不需要每次使用组件时都指定.default。