傳統js和jsx與ts和tsx的區別


一、從定義文件格式方面說

1、傳統的開發模式可以定義js文件或者jsx文件
2、利用ts開發定義的文件格式tsx
二、定義state的狀態來說

1、傳統的方式直接在構造函數中使用

constructor(){
    this.state = {
        num1:10
    }
}

 


2、使用ts開發過程中需要先定義一個接口,規范數據類型,通過泛型傳入到類中

//定義一個接口規范state的類型  

export interface State{
    num1:number
}

 


// 默認導出一個Hello類,如果Component<Props,State>里面沒有就用object

export default class Hello extends React.Component<Props,State>{
    constructor(props:Props){
        super(props);
        this.state = {
            num1:10
        }
    }
}

 


 

三、父組件傳遞參數到子組件

1、傳統的方式直接使用就可以,如果要約束數據類型參考文檔
2、使用ts開發方式,跟上面的state一樣的,只是不管怎么樣都要在構造函數中寫super
四、從獲取真實的DOM節點上來說(關於為什么要在componentDidMount中獲取請參考參考)

1、傳統的方式直接在DOM節點上定義ref就可以生命周期鈎子函數componentDidMount中獲取

    

const myref= this.refs.refname;
    const myrefdom = findDOMNode(myref);

 

2、在ts中獲取ref節點的方式

import * as ReactDOM from 'react-dom';
componentDidMount(){
    console.log(`componentDidMount方法`);
    var myp = ReactDOM.findDOMNode<HTMLInputElement>(this.refs["myp"]);
    console.log(myp.innerText);
}

五、直接獲取DOM節點

1、傳統的方式

let pDom = document.querySelector("p");
pDom.addEventListener('click',()=>{
    console.log('你點擊了我');
})

 

2、在ts中根據上面的方式可以獲取pDom但是綁定事件的時候就是null

var myp = ReactDOM.findDOMNode<HTMLInputElement>(this.refs["myp"]);
myp.addEventListener('click',()=>{
    console.log('你點擊了我');
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM