簡體   English   中英

打字稿中的界面狀態和道具反應

[英]interface states and props in typescript react

我正在開發一個使用 TypeScript 和 React 的項目,我對這兩個項目都很陌生。 我的問題是關於 TypeScript 中的接口以及它與道具和狀態的關系。 實際發生了什么? 除非我聲明接口道具和狀態,否則我的應用程序根本不會運行,但是我通過 React 構造函數使用狀態,並且我已經看到所有這些信息都將進入“interface MyProps”或“interface MyStates”的示例. 以這段代碼為例:

"use strict";

import * as React from 'react'
import NavBar from './components/navbar.tsx'
import Jumbotron from './components/jumbotron.tsx';
import ContentPanel from './components/contentPanel.tsx';
import Footer from './components/footer.tsx';

interface MyProps {}
interface MyState {}
class Root extends React.Component <MyProps, MyState>  {
  constructor(props) {
    super(props);
    this.state = {
      ///some stuff in here
  
    };
  }
  render() {
    return (
      <div>
        <NavBar/>
        <Jumbotron content={this.state.hero}/>
        <ContentPanel content={this.state.whatIs}/>
        <ContentPanel content={this.state.aboutOne}/>
        <ContentPanel content={this.state.aboutTwo}/>
        <ContentPanel content={this.state.testimonial}/>
        <Footer content={this.state.footer}/>
      </div>
    )
  }
}
export default Root;

(我已經刪除了 this.state 中的內容只是為了在這里發布)。 為什么需要接口? 這樣做的正確方法是什么,因為我認為我正在以 JSX 方式而不是 TSX 方式考慮這一點。

目前還不清楚你在問什么,但是:

props:是從組件的父組件傳遞的鍵/值對,組件不應更改它自己的 props,只對來自父組件的 props 的更改做出反應。

state:有點像 props,但它們在組件本身中使用setState方法進行了更改。

當 props 或 state 改變時調用render方法。

至於打字稿部分, React.Component采用兩種類型作為泛型,一種用於道具,一種用於狀態,您的示例應該看起來更像:

interface MyProps {}

interface MyState {
    hero: string;
    whatIs: string;
    aboutOne: string;
    aboutTwo: string;
    testimonial: string;
    footer: string;
}

class Root extends React.Component <MyProps, MyState>  {
    constructor(props) {
        super(props);

        this.state = {
            // populate state fields according to props fields
        };
    }

    render() {
        return (
            <div>
                <NavBar/>
                <Jumbotron content={ this.state.hero } />
                <ContentPanel content={ this.state.whatIs } />
                <ContentPanel content={ this.state.aboutOne } />
                <ContentPanel content={ this.state.aboutTwo } />
                <ContentPanel content={ this.state.testimonial } />
                <Footer content={ this.state.footer } />
            </div>
        )
    }
}

如您所見, MyState接口定義了稍后在組件this.state成員中使用的字段(我將它們全部this.state字符串,但它們可以是您想要的任何內容)。

我不確定這些字段是否真的需要在 state 中而不是在 props 中,但這是你的要求。

1 - 如果您不想要,請刪除您的界面。並在您的課程中聲明狀態
2 - 改變類擴展如下

class Root擴展了React.Component <{},{}> {

.........

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM