react+typescript学习记录

本文深入讲解React结合TypeScript的使用技巧,从基础的Hello World示例开始,逐步介绍元素渲染、函数与Class组件的区别,以及State与生命周期管理。通过具体代码示例,帮助读者理解如何在React应用中有效运用TypeScript,提升代码质量和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react 学习记录(typescript)

1.hello world(第一个例子)

import * as React from 'react'
class HelloWorld extends React.Component{   
    render():
    {   
        return <h1>hello World</h1>;
    }
}
export  default  HelloWorld

2.元素渲染

想要将一个 React 元素渲染到根 DOM 节点中,只需把它们一起传入 ReactDOM.render()

const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));

React 元素是不可变对象。一旦被创建,你就无法更改它的子元素或者属性。一个元素就像电影的单帧:它代表了某个特定时刻的 UI。

根据我们已有的知识,更新 UI 唯一的方式是创建一个全新的元素,并将其传入 ReactDOM.render()

3.函数组件与 class 组件

​ 3.1 函数组件:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

3.2 ES6 的 class来定义组件:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

4.State & 生命周期

import * as React from 'react'
import dayjs from 'dayjs'
interface Props { }
interface State {    
    date: any
}
class HelloWorld extends React.Component<Props,State>{   
    timerID: any   
    constructor(props: Props) 
    {       
        super(props);       
        this.state ={date: new Date()};
    }   
    componentDidMount() {   
        this.timerID = setInterval(   
            () => this.tick(),   
            1000        );  
    }    
    componentWillUnmount() {      
        clearInterval(this.timerID); 
    }    
    tick() {        
        this.setState({           
            date: new Date()       
        });   
    }    
    render() {       
        return (
            <div> 
                <h1>Hello, world!</h1> 
                <h2>It is { dayjs(this.state.date).format('YYYY-MM-DD HH:mm:ss') }</h2>        		  </div>
        );    }
}
export  default  HelloWorld
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有志青年(top)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值