尝试将useState与类型一起使用

时间:2019-06-11 17:58:05

标签: reactjs typescript

import React, { Component } from 'react'

interface orderInformation {
    customer: number;
    picklePrice: number;
    breadPrice: number;

}

interface ComponentState
{
    customer: number;
    picklePrice: number;
    breadPrice: number;
}

export default class pickleSandwich extends Component<orderInformation,ComponentState> {

    const [customer, setCustomer] = useState(0);

//Get information for the user
getInfo = orderInformation => {
        orderInformation.preventDefault();


      };

render() {
        return (
            <div>

            </div>
        );
}
}

我目前正在学习打字稿,但是我找不到任何可以满足我的需求的好例子。我所能找到的只是字符串示例,在这种情况下,我使用的是类型编号。     尝试使用React Hooks来消耗此信息。

1 个答案:

答案 0 :(得分:2)

如果您想使用钩子,那就是这样:

import React from 'react'

interface orderInformation {
    customer: number;
    picklePrice: number;
    breadPrice: number;

}

interface ComponentState {
    customer: number;
    picklePrice: number;
    breadPrice: number;
}

const PickleSandwich = (props:orderInformation) =>  {

    const [customer, setCustomer] = useState<ComponentState>("valid_state");

    //Get information for the user
    getInfo = orderInformation => {
        orderInformation.preventDefault();
    };

    return <div />

}

但是,如果您要使用类,您将走上正确的道路,但在类中您将无法使用钩子,那么您需要使用:

state = {your_state}