Regarding the “Random Color” Project for React Part I
At the end, there is a <Button>
described as such: <Button onClick={this.handleClick} light={this.isLight()} />
When <Button>
uses this.isLight()
it requires parenthesis, however the event handler does not use parens, it just has this.handleClick
.
It is my understanding that this.functionName()
is a call to the function and just this.functionName
is a reference to the object for the function (at least in Python).
But I feel like it should be the same for both. Why is the syntax different here?
Full Code Below
Random.js
var React = require('react');
var ReactDOM = require('react-dom');
var Button = require('./Button');
var Random = React.createClass({
getInitialState: function () {
return {
color: [0, 0, 0]
};
},
handleClick: function () {
this.setState({
color: this.chooseColor()
})
},
componentDidMount: function () {
this.applyColor();
},
componentDidUpdate: function (prevProps, prevState) {
this.applyColor();
},
formatColor: function (ary) {
return 'rgb(' + ary.join(', ') + ')';
},
isLight: function () {
var rgb = this.state.color;
return rgb.reduce(function(a,b){ return a+b; }) < 127 * 3;
},
applyColor: function () {
var color = this.formatColor(this.state.color);
document.body.style.background = color;
},
chooseColor: function () {
for (var i = 0, random = []; i < 3; i++) {
random.push(Math.floor(Math.random()*256));
}
return random;
},
render: function () {
return (
<div>
<h1 className={this.isLight() ? 'white' : 'black'}>
Your color is {this.formatColor(this.state.color)}!
</h1>
<Button onClick={this.handleClick} light={this.isLight()} />
</div>
);
}
});
ReactDOM.render(
<Random />,
document.getElementById('app')
);
Button.js
import React from 'react';
export class Button extends React.Component {
render() {
return (
<button
className={ this.props.light ? 'light-button' : 'dark-button' } onClick={this.props.onClick}>
Refresh
</button>
);
}
}