Jim*_*imi 12 typescript reactjs
我从反应组件中得到了一个ts错误.组件运行正常,构建等,但是typescript在ide中显示错误.不知道我需要如何声明这个以消除错误.我试图在组件本身内部创建一个setState方法,但这会产生更多错误.
错误:(15,19)TS2605:JSX元素类型'Home'不是JSX元素的构造函数."Home"类型中缺少属性"setState".
"typescript":"^ 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 />, <<<<
}
Run Code Online (Sandbox Code Playgroud)
- 其余部分为简洁而删除
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>
}
}
Run Code Online (Sandbox Code Playgroud)
遇到了同样的问题,但是我的问题是我导入了React错误。
使用TypeScript时导入的正确方法是使用import * as React from "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"))
Run Code Online (Sandbox Code Playgroud)
注意: <any, any>允许您在React组件中使用任何props和state变量,但是通常应该自己定义它们,以利用TypeScript的类型注释。
以下是如何使用状态和渲染组件的示例:
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 } />
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,道具和状态对象总是很简单,渲染方法负责创建实际的组件。
这样 React 就知道哪些组件发生了变化以及 DOM 树的哪些部分应该更新。
| 归档时间: |
|
| 查看次数: |
11365 次 |
| 最近记录: |