且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Reactj,类型中缺少打字稿属性“setState"

更新时间:2022-01-09 22:09:40

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

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.