TypeScriptとReactを学習中で、Reactの公式ドキュメントに載っているコードをTypeScriptで書いてみているのですが、
このページに載っている、時計機能のコードで行き詰まっています。
TypeScript
1import * as React from 'react'; 2import * as ReactDOM from 'react-dom'; 3 4interface clockState { 5 date: Date 6} 7 8class Clock extends React.Component<clockState> { 9 constructor(props) { 10 super(props); 11 this.state = {date: new Date()}; 12 } 13 14 componentDidMount() { 15 this.timerId = setInterval( 16 () => this.tick(), 17 1000 18 ); 19 } 20 21 componentWillUnmount() { 22 clearInterval(this.timerId); 23 } 24 25 tick() { 26 this.setState({ 27 date: new Date() 28 }); 29 } 30 31 render() { 32 return ( 33 <div> 34 <h1>Hello, world!</h1> 35 <h2>It is {this.state.date.toLocaleTimeString()}.</h2> 36 </div> 37 ); 38 } 39 } 40 41 ReactDOM.render( 42 <Clock />, 43 document.getElementById('root') 44 );
この状態では timerId
の型が定義されていないのでエラーとなるのですが、
TypeScriptではどこで timerId
を定義すればよいのでしょうか?
prop
として定義するとread-onlyになってしまうので、後で setInterval
の処理を行うことができません。
state
として定義する場合、 clearInterval
の処理をどう行えばいいかよくわかっていません。
どのように書くとよいでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/01 07:26