【问题标题】:How to avoid repeating interface in Typescript React如何避免 Typescript React 中的重复界面
【发布时间】:2019-02-03 11:05:11
【问题描述】:

这是我尝试使用 Typescript 构建的第一个应用程序。我想将样式和组件保存在单独的文件中,以使代码更具描述性和清晰性。项目将包含几十个组件,我将使用道具来调用这些类。每个组件看起来或多或少是这样的:

import * as React from 'react'
import withStyles from "@material-ui/core/styles/withStyles"
import { LandingPageStyles } from "./landing-page-styles"

interface LandingPageProps {
  classes: any
}

class LandingPage extends React.Component<LandingPageProps> {

  get classes() {
    return this.props.classes;
  }

  render() {
    return(
      <div className={this.classes.mainPage}>
        Hello Typescript
      </div>
    ) 
  }
}

export default withStyles(LandingPageStyles)(LandingPage)

以及简化样式模块:

import { createStyles } from "@material-ui/core";

export const LandingPageStyles = () => createStyles({
  mainPage: {
    textAlign: "center",
    minHeight: "100vh",
  }
})

在每个组件中,我都希望拥有类型为 any 的类道具。有没有办法避免为每个组件声明接口?它现在可以工作,但我不喜欢我当前的解决方案,因为在每个组件中重复相同的代码。

【问题讨论】:

    标签: reactjs typescript material-ui typescript-typings


    【解决方案1】:

    正确的做法如下。 Material-ui 暴露WithStyles 接口,您可以继承该接口以包含classes 道具。主要优点是您的 IDE 将处理定义的 jss 类的自动完成。但无论如何,Typescript 比 Javacript 更冗长。使用 React,您经常需要重复一些显而易见的事情。

    import * as React from 'react'
    import {withStyles, WithStyles} from "@material-ui/core"
    import { LandingPageStyles } from "./landing-page-styles"
    
    interface LandingPageProps extends WithStyles<typeof LandingPageStyles> {
    }
    
    class LandingPage extends React.Component<LandingPageProps> {
    
      get classes() {
        return this.props.classes;
      }
    
      render() {
        return(
          <div className={this.classes.mainPage}>
            Hello Typescript
          </div>
        ) 
      }
    }
    
    export default withStyles(LandingPageStyles)(LandingPage)
    

    【讨论】:

      【解决方案2】:

      最好的解决方案是声明扩展 WithStyles 的接口。所以在组件中需要声明:

      import * as React from 'react'
      import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"
      import { LandingPageStyles } from "./landing-page-styles"
      
      interface LandingPageProps extends WithStyles<typeof LandingPageStyles>{
      
      }
      class LandingPage extends React.Component<LandingPageProps> {
      
        get classes() {
          return this.props.classes;
        }
      
        render() {
          return(
            <div className={this.classes.mainPage}>
              Hello Typescript
            </div>
          ) 
        }
      }
      
      export default withStyles(LandingPageStyles)(LandingPage)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-23
        • 2020-01-01
        • 2020-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多