我的react组件出现ts错误。组件运行良好,正在构建等,但是typescript在ide中显示错误。不确定我需要如何声明以删除错误。我试图在组件本身内部创建一个setState方法,但这会产生更多的错误。
错误:(15,19)TS2605: JSX元素类型'Home'不是JSX元素的构造函数。属性setState在类型Home中丢失。
“类型脚本”:“^2.3.4”,
“反应”:“^15.5.4”,
"react-dom":"^15.5.4",
!----
export class App extends React.Component<Props, State> {
public state: State
public props: Props
constructor(props: Props) {
super(props)
this.state = {
view: <Home />, <<<<
}
--为了简洁起见,其余的都去掉了
export class Home extends React.Component<Props, State> {
public state: State;
public props: Props;
constructor(props: Props) {
super(props)
}
public render() {
return <h1>home</h1>
}
}
我也有同样的问题,但我的问题是我错了。
使用TypeScript时,正确的导入方法是使用import*作为“React”
中的React。
代码示例:
import * as React from "react"
import ReactDOM from "react-dom"
class App extends React.Component<any, any> {
render() {
return (
<div>Hello, World!</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"))
注:
下面是如何使用状态和呈现组件的示例:
type HomeProps = {
text: string;
}
class Home extends React.Component<HomeProps, void> {
public render() {
return <h1>{ this.props.text }</h1>
}
}
type AppState = {
homeText: string;
}
class App extends React.Component<void, AppState> {
constructor() {
super();
this.state = {
homeText: "home"
};
setTimeout(() => {
this.setState({ homeText: "home after change "});
}, 1000);
}
render() {
return <Home text={ this.state.homeText } />
}
}
如您所见,道具和状态对象始终很简单,渲染方法负责创建实际组件
通过这种方式,react知道哪些组件已更改,以及DOM树的哪些部分应更新。