I participated in the React Hands-on so I would like to leave that memorandum.
React initial setting
- Installation
$ npm install -g create-react-app
- Establishment of the environment at the workplace
$ create-react-app myapp
$ cd myapp
$ npm start
- Route point
ReactDOM.render(
<App />,
document.getElementById('root')
);
Make characters tick
· How to write characters using the setInterval function
import React, { Component } from 'react';
import Text from './Text';
class App extends Component {
render() {
return (
<div>
<Text text='sentence' />
</div>
)
}
}
export default App;
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;
Click count
import React, { Component } from 'react';
import Button from './Button';
class App extends Component {
render() {
return (
<div>
<Button />
</div>
)
}
}
export default App;
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;
How to write other bind
· Write onClick
<button onClick={this._addCount.bind(this)}>
· Write with arrow function (bind unnecessary)
_addCount = () => {
this.setState({
count: this.state.count + 1,
});
}