我写了一些代码:
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没有任何构造或调用签名
这是什么意思?
当前回答
你可以使用
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>;
}
其他回答
如果你正在使用一个功能组件,并传递一个组件作为道具,对我来说,解决方案是改变React。ReactNode to React。应用的
interface Props{
GraphComp: React.ElementType
}
const GraphCard:React.FC<Props> = (props) => {
const { GraphComp } = props;
return (
<div> <GraphComp /> </div>
)
}
当声明React Class组件时,使用React。ComponentClass而不是React。组件,那么它将修复ts错误。
如果你想把一个组件类作为参数(而不是一个实例),使用React。ComponentClass:
function renderGreeting(Elem: React.ComponentClass<any>) {
return <span>Hello, <Elem />!</span>;
}
这是语法的问题
下面是一个使用TSX的例子:
const SomeMadeComponent = (props: { someText: string }) => {
const { someText} = props;
return (
<div>
<p>{someText}</p>
</div>
);
};
你可以像使用普通组件一样使用它:
<SomeMadeComponent someText='把你的文本放在这里' />
在我的例子中,我在类型定义中缺少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} />