Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created January 30, 2018 23:22
Show Gist options
  • Save pinkmomo027/6a92d2dcfcea9808205aecbb7fd68782 to your computer and use it in GitHub Desktop.
Save pinkmomo027/6a92d2dcfcea9808205aecbb7fd68782 to your computer and use it in GitHub Desktop.
// SyntheticEvent
// 'this' inside your event handler refers to the component the event handler lives in
class PlusButton extends React.Component {
render(){
const buttonStyle= {
fontSize: '1em',
width: 30,
height: 30,
fontFamily: 'sens-serif',
color: "#333",
fontWeight: 'bold',
lineHeight: '3px'
}
return (
<button style={buttonStyle} onClick={this.props.clickHandler}>
+
</button>
)
}
}
class Counter extends React.Component {
render() {
const textStyle = {
fontSize: 38,
fontFamily: 'sans-serif',
color: "#333",
fontWeight: 'bold'
}
return (
<div style={textStyle}>
{this.props.count}
</div>
)
}
}
class CounterDisplay extends React.Component {
constructor(props){
super(props);
this.state = {
count: 0
}
this.increase = this.increase.bind(this);
}
increase(e) {
// 'this' here refers to CounterDisplay, not button
// because in the constructor we 'bind' it to the component
let increment;
increment = e.shiftKey? 10 : 1;
this.setState(prevState => ({
count: prevState.count + increment
}));
// this.setState({
// count: this.state.count+1
// });
}
render() {
const divStyle= {
width: 200,
height:100,
backgroundColor: 'lightblue',
borderRadius: 10,
textAlign: 'center',
paddingTop: 50
}
return (
<div>
<div style={divStyle}>
<Counter count={this.state.count} />
<PlusButton clickHandler={this.increase} />
</div>
<p>Increment by 10 when Shift is pressed</p>
</div>
);
}
}
ReactDOM.render(<CounterDisplay />, document.querySelector('#root'));
// HTML
// <div id="root"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment