我正在做一个既使用TypeScript又使用React的项目,我对这两者都是新手.我的问题是关于TypeScript中的接口,以及它与props 和状态的关系.到底发生了什么?除非我声明接口props 和状态,否则我的应用程序根本不会运行,但我通过React构造函数使用状态,我见过一些例子,其中所有信息都会进入"接口MyProps"或"接口MyState".以这段代码为例:

"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 的更改做出react .

状态:有点像props ,但它们在组件本身中使用setState方法进行更改.

当props 或状态发生变化时,调用render方法.

至于typescript部分,React.Component采用两种类型作为泛型,一种用于props ,另一种用于状态,您的示例应该更像:

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接口定义了后来在component this.state成员中使用的字段(我将它们都设置为字符串,但它们可以是您想要的任何内容).

我不确定这些字段是否真的需要在状态中,而不是在props 中,但这是你需要做的.

Typescript相关问答推荐

为什么缩小封闭内部不适用于属性对象,但适用于声明的变量?

如何将联合文字类型限制为文字类型之一

学习Angular :无法读取未定义的属性(正在读取推送)

为什么有条件渲染会导致material 自动完成中出现奇怪的动画?

TypeScrip泛型类未提供预期的类型错误

FatalError:Error TS6046:';--模块分辨率';选项的参数必须是:'; node ';,'; node 16';,'; node

在React中定义props 的不同方式.FunctionalComponent

判断映射类型内的键值的条件类型

如何在脚本中输入具有不同数量的泛型类型变量的函数?

类型脚本-在调用期间解析函数参数类型

如何在不违反挂钩规则的情况下动态更改显示内容(带有状态)?

如果判断空值,则基本类型Gaurd不起作用

如何键入对象转换器

基于泛型的类型脚本修改类型

窄SomeType与SomeType[]

使用受保护的路由和入门来响应路由

根据索引将元组拆分为两个块

在 next.js 13.4 中为react-email-editor使用forwardRef和next/dynamic的正确方法

如何将参数传递给条件函数类型

有效索引元组的Typescript 类型?