react+typescript学习记录

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
posted @ 2020-01-01 20:44  it_dog_zhang  阅读(393)  评论(0)    收藏  举报