Reactj,类型中缺少打字稿属性“setState" [英] Reactj, typescript Property 'setState' is missing in type

查看:33
本文介绍了Reactj,类型中缺少打字稿属性“setState"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 react 组件出现 ts 错误.该组件运行良好,正在构建等,但是 typescript 在 ide 中显示错误.不知道我需要如何声明以消除错误.我尝试在组件内部创建一个 setState 方法,但这会产生更多错误.

I'm getting a ts error from my react component. The component is running fine, building etc, however typescript is showing an error inside the ide. Not sure how i need to declare this to remove the error. I've tried to create a setState method inside the component itself, but this was giving even more errors.

错误:(15, 19) TS2605:JSX 元素类型Home"不是构造函数JSX 元素的函数.类型中缺少属性setState"家".

Error:(15, 19) TS2605:JSX element type 'Home' is not a constructor function for JSX elements. Property 'setState' is missing in type 'Home'.

"打字稿": "^2.3.4",

"typescript": "^2.3.4",

反应":^15.5.4",

"react": "^15.5.4",

"react-dom": "^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 />, <<<<
    } 

-- 为简洁起见,其余部分已删除

-- the rest removed for brevity

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>
  }
}

推荐答案

以下是如何使用状态和渲染组件的示例:

Here's an example of how to use the state and render the components:

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 } />
    }
}

如您所见,props 和 state 对象总是很简单,渲染方法负责创建实际组件.
这样 react 就知道哪些组件发生了变化,DOM 树的哪些部分应该更新.

As you can see, the props and state objects are always simple, and the rendering method is in charge of creating the actual components.
This way react knows which components are changed and which parts of the DOM tree should be updated.

这篇关于Reactj,类型中缺少打字稿属性“setState"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆