在React中使用TypeScript

以下面这种方式创建React项目

npx create-react-app my-app --template typescript

Class组件
import * as React from "react";
 
//props
export interface IHomePageProps {
    home: string;
}
//state
export interface IHomePageState {
    name: string;
    num: number;
}
   
class Content extends React.Component<IHomePageProps, IHomePageState> {
    constructor(props: IHomePageProps) {
        super(props);
        this.state = {
            name: "",
            num: 999
        };
    }
    componentWillMount = () => {

    }
    public setName = (): void => {
        this.setState({
            name: "icepy"
        });
    }

    public render(){
        const { name, num } = this.state;
        const { home } = this.props;
        return (
            <div>
                <div onClick={this.setName}> set name </div>
                <div>{name}</div>
                <div>{home}</div>
                <div>{num}</div>
            </div>
        )
    }
}
 
export default Content;

猜你喜欢

转载自blog.csdn.net/weixin_45679977/article/details/105197599