我有以下 app.tsx 文件,可以很好地从 React.Component 加载一个 App 元素,并从另一个 React.Component 加载一个子 Worklist 元素(两个类都在同一个 app.tsx 文件中定义)。这是在安装了 Typescript 1.6 的 Visual Studio 中运行的(ECMAScript 版本:ECMAScript 5,JSX 编译:React,模块系统:CommonJS)。
但是,我想将这两个组件拆分成单独的文件。但是,当我取消注释 WorkList 的导入并从 app.tsx 中删除 WorkList 组件的类定义时 - 它失败并出现错误:
Error TS2604 JSX element type 'WorkList' does not have any construct or call signatures.
这是工作的 app.tsx 和所需的 worklist.tsx。
// app.tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
//import * as WorkList from "./worklist";
interface Props {
foo: string;
}
class WorkList extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
render() {
return <h2>WorkList!{this.props.foo} </h2>
}
}
class App extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
public render() {
return <WorkList foo="baz"></WorkList>
}
}
ReactDOM.render(
React.createElement(App, { foo: 'bar' }),
document.getElementById('app')
);
//worklist.tsx
import * as React from "react";
interface Props {
foo: string;
}
class WorkList extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
render() {
return <h2>WorkList!{this.props.foo} </h2>
}
}
<WorkList foo="bar" />
用 Typescript 1.6 导入子 JSX 的正确方法是什么?
这是应用了正确答案的工作代码:
// app.tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
import WorkList from "./worklist";
interface Props {
foo: string;
}
class App extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
public render() {
return <WorkList foo="baz"></WorkList>
}
}
ReactDOM.render(
React.createElement(App, { foo: 'bar' }),
document.getElementById('app')
);
//worklist.tsx
import * as React from "react";
interface Props {
foo: string;
}
export default class WorkList extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
render() {
return <h2>WorkList!{this.props.foo} </h2>
}
}
最佳答案
我希望您需要在 worklist.tsx
文件中正确导出 WorkList
类,例如作为默认导出:
export default class WorkList extend React.Component<Props, {}>
然后在app.tsx
中导入:
import WorkList from "worklist"
这应该可以解决您的问题。
关于typescript - 如何从 Typescript 1.6 中的单独文件正确导入 React JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33456231/