Reactハンズオンに参加したのでその備忘録を残したいと思います。
React初期設定
・インストール
command
$ npm install -g create-react-app
・作業場で環境構築
command
$ create-react-app myapp
$ cd myapp
$ npm start
・ルートポイント
src/index.js
ReactDOM.render(
<App />,
document.getElementById('root')
);
文字をチカチカさせる
・setInterval関数を使って文字をチカチカさせる書き方
src/App.js
import React, { Component } from 'react';
import Text from './Text';
class App extends Component {
render() {
return (
<div>
<Text text='チカチカ文字' />
</div>
)
}
}
export default App;
src/Text.js
import React, { Component } from 'react';
class Text extends Component {
constructor(props) {
super(props);
this.state = {
showText: true,
};
setInterval(() => {
this.setState({
showText: !this.state.showText,
});
}, 1000);
}
render() {
const text = this.state.showText? this.props.text : '';
return (
<div>
{text}
</div>
)
}
}
export default Text;
クリックカウント
src/App.js
import React, { Component } from 'react';
import Button from './Button';
class App extends Component {
render() {
return (
<div>
<Button />
</div>
)
}
}
export default App;
src/Button.js
import React, { Component } from 'react';
class Button extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
}
this._addCount = this._addCount.bind(this); // イベントハンドラでthisをbindさせるため
}
_addCount() {
this.setState({
count: this.state.count + 1,
});
}
render() {
return (
<div>
<button onClick={this._addCount}>
button
</button>
<p>{this.state.count}</p>
</div>
)
}
}
export default Button;
その他のbindの書き方
・onClickに書く
src/Button.js
<button onClick={this._addCount.bind(this)}>
・arrow functionで書く(bind不要)
src/Button.js
_addCount = () => {
this.setState({
count: this.state.count + 1,
});
}