Skip to content

Instantly share code, notes, and snippets.

@castaneai
Created February 27, 2015 10:27
Show Gist options
  • Save castaneai/9ce7815aba7f1024038d to your computer and use it in GitHub Desktop.
Save castaneai/9ce7815aba7f1024038d to your computer and use it in GitHub Desktop.
React.js (ES6) Simple Counter
class App extends React.Component {
constructor(props) {
this.state = {
count: 0
}
}
onClick(e) {
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.onClick.bind(this)}>Count Up!!</button>
</div>
)
}
}
React.render(
<App/>,
document.getElementById('app-container')
);
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>React Test</title>
<script src="http://fb.me/react-with-addons-0.13.0-rc1.min.js"></script>
<script src="http://fb.me/JSXTransformer-0.13.0-rc1.js"></script>
<script src="app.jsx" type="text/jsx;harmony=true"></script>
<head>
<body>
<div id="app-container"></div>
</body>
</html>
@leyaannie
Copy link

this program is not correct

@fanux365
Copy link

fanux365 commented Apr 14, 2018

https://reactjs.org/docs/state-and-lifecycle.html

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment