ReactJS 元件用 Typescript 編寫

你可以在 TypeScript 中輕鬆使用 ReactJS 的元件。只需將’jsx’副檔名重新命名為’tsx’即可:

//helloMessage.tsx:
var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

ReactDOM.render(<HelloMessage name="John" />, mountNode);

但是為了充分利用 TypeScript 的主要功能(靜態型別檢查),你必須做一些事情:

1)將 React.createClass 轉換為 ES6 類:

//helloMessage.tsx:
class HelloMessage extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

ReactDOM.render(<HelloMessage name="John" />, mountNode);

有關轉換為 ES6 的更多資訊,請檢視此處

2)新增道具和狀態介面:

interface Props {
    name:string;
    optionalParam?:number;
}

interface State {
  //empty in our case
}

class HelloMessage extends React.Component<Props, State> {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}
// TypeScript will allow you to create without the optional parameter
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
// But it does check if you pass in an optional parameter of the wrong type
ReactDOM.render(<HelloMessage name="Sebastian" optionalParam='foo' />, mountNode);

現在,如果程式設計師忘記傳遞道具,TypeScript 將顯示錯誤。或者,如果嘗試傳入未在介面中定義的道具。