简体   繁体   English

我可以在不更改界面的情况下为 React Typescript 中的状态添加多个变量吗?

[英]Can I add multiple variables for the state in React Typescript without changing the interface?

I am trying to add a variable to the state of a react component.我正在尝试向反应组件的状态添加一个变量。 This is how the component looks:这是组件的外观:

export class Item extends React.Component<{}, State>{
    now: Date;
    constructor(props: any) {
        super(props);
        this.state = {
            tab: Tabs.example,
            e1: {},
            e2: {},
            e3: {},
            e4: {},
            e5: {},
            e6: {},
            e7: {},
            e8: {},
            e9: {}
        }
        this.now = new Date();

    }

The interface State is already defined as接口状态已经定义为

interface State {
tab: Tabs
e1: any
e2: any
e3: any
e4: any
e5: any
e6: any
e7: any
e8: any
e9: any
}

I would like to add another object foo to the state of my component 'Item' but I cannot change the interface.我想将另一个对象foo添加到我的组件“Item”的状态,但我无法更改界面。 Is there a way to add foo: any to the state variables without messing up the interface?有没有办法在不弄乱界面的情况下将foo: any添加到状态变量中?

You could try extending the interface so that you can maintain type safety/strictness - which helps devs (or at least me) stay sane with javascript and reap the benefits of typescript您可以尝试扩展接口,以便您可以保持类型安全/严格性 - 这有助于开发人员(或至少我)使用 javascript 保持理智并获得打字稿的好处

interface StateWithFoo extends State{
  foo: any
}

export class Item extends React.Component<{}, StateWithFoo>{

There are other ways if extending isn't an option;如果扩展不是一种选择,还有其他方法; you could try using Partial or other TypeScript features, each coming with some tradeoff.您可以尝试使用 Partial 或其他 TypeScript 功能,每个功能都有一些权衡。

I lead with the extending interface approach since it maintains type safety/strictness, but if that doesn't work we can discuss other options我采用扩展接口方法,因为它保持了类型安全/严格性,但如果这不起作用,我们可以讨论其他选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM