【问题标题】:Can we implement interface for react state attributes in typescript?我们可以在打字稿中实现反应状态属性的接口吗?
【发布时间】:2021-04-20 10:23:46
【问题描述】:

我有以下代码

interface inputElementProperties {
    elementType: "input",
    elementConfig: {
        Type: "text",
        placeholder: "",
    },
    value: "",
    validations: {
        maxLength: 100,
    },
    valid: true,
    touched: false,
    shouldValidate: false
}


class Home extends React.Component<inputElementProperties>{

    constructor(props) {
        super(props);
        this.state = {
            cardOne: {
                Company: inputElementProperties{
                    elementType: "input",
                    elementConfig: {
                        Type: "checkbox",
                        placeholder: "",
                    },
                    value: "",
                    shouldValidate: false,
                    touched: false,
                    valid:true
                },
                Prefix: {
                    elementType: "input",
                    elementConfig: {
                        Type: "text",
                        placeholder: "",
                    },
                    value: "",
                    validations: {
                        maxLength: 10,
                    },
                    valid: true,
                    touched: false,
                    shouldValidate: true
                }
            }
       }
}

我想对 state 中 cardOne 属性的每个属性实现 inputElementProperties。

得到错误,例如:inputElementProperties 指的是一个类型,但被用作一个值

【问题讨论】:

    标签: reactjs typescript react-redux


    【解决方案1】:

    试试这个:

    interface Props {
      // ...
    }
    
    interface State {
      // HERE YOU CAN USE THE Props INTERFACE
      // IF THAT IS WHAT YOU NEED
    }
    
    
    class Home extends React.Component<Props,State> {
    
        constructor(props) {
            super(props);
            this.state;     // THIS SHOULD BE TYPE State
            this.props;     // THIS SHOULD BE TYPE Props
        }
    }
    

    您还可以查看有关此示例的更多详细信息:link

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2016-04-04
      • 2011-04-17
      • 1970-01-01
      • 2015-11-10
      • 2023-01-23
      相关资源
      最近更新 更多