小编典典

Reactj,打字稿属性'setState'在类型中丢失

reactjs

我的React组件出现了TS错误。组件运行正常,正在构建等,但是打字稿在ide内部显示错误。不知道我该怎么声明才能消除错误。我试图在组件本身内部创建一个setState方法,但这会带来更多错误。

错误:(15、19)TS2605:JSX元素类型’Home’不是JSX元素的构造函数。类型“ Home”中缺少属性“ setState”。

“ typescript”:“ ^ 2.3.4”,

“ react”:“ ^ 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>
  }
}

阅读 261

收藏
2020-07-22

共1个答案

小编典典

这是一个如何使用状态并渲染组件的示例:

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树的哪些部分应更新。

2020-07-22