Common html using in 3 examples in this article:
<div id="root"></div>
JavaScript
Method 1) bind this in contructor
class Button extends React.Component {
constructor(props){
super(props);
this.state = {isOn:true};
this.buttonClick = this.buttonClick.bind(this);
}
buttonClick(){
if(this.state.isOn)
this.setState({"isOn":false});
else
this.setState({"isOn":true});
}
render() {
return (
<button onClick={this.buttonClick}>
{this.state.isOn?"ON":"OFF"}
</button>
);
}
}
ReactDOM.render(<Button />,document.getElementById('root'));
Method 2) bind this within handleClick
class Button extends React.Component {
constructor(props){
super(props);
this.state = {isOn:true};
}
buttonClick = ()=>{
if(this.state.isOn)
this.setState({"isOn":false});
else
this.setState({"isOn":true});
}
render() {
return (
<button onClick={this.buttonClick}>
{this.state.isOn?"ON":"OFF"}
</button>
);
}
}
ReactDOM.render(<Button />,document.getElementById('root'));
Method 3) using experimental syntax
class Button extends React.Component {
constructor(props){
super(props);
this.state = {isOn:true};
}
buttonClick(){
if(this.state.isOn)
this.setState({"isOn":false});
else
this.setState({"isOn":true});
}
render() {
return (
<button onClick={(e)=>{this.buttonClick(e)}}>
{this.state.isOn?"ON":"OFF"}
</button>
);
}
}
ReactDOM.render(<Button />,document.getElementById('root'));
No comments :
Post a Comment