From dd5a665d42b95d3cbe5ab5bcb5437e3e610c096e Mon Sep 17 00:00:00 2001 From: Chris Date: Sun, 11 Dec 2016 21:41:48 +0800 Subject: [PATCH] update example to use `this.state` (#8425) - In the previous example, the code works even without using bind(this) in the constructor. - the reason being handleClick doesn't even use `this` and its just calling the global function alert. - this change make use of this via access this.state. --- docs/react-without-es6.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/react-without-es6.md b/docs/react-without-es6.md index 3921f0f21..ac92533b7 100644 --- a/docs/react-without-es6.md +++ b/docs/react-without-es6.md @@ -97,12 +97,13 @@ In React components declared as ES6 classes, methods follow the same semantics a class SayHello extends React.Component { constructor(props) { super(props); + this.state = { message: 'Hello!' }; // This line is important! this.handleClick = this.handleClick.bind(this); } handleClick() { - alert('Hello!'); + alert(this.state.message); } render() { @@ -120,8 +121,12 @@ With `React.createClass()`, this is not necessary because it binds all methods: ```javascript var SayHello = React.createClass({ + getInitialState: function() { + return { message: 'Hello!' }; + }, + handleClick: function() { - alert('Hello!'); + alert(this.state.message); }, render: function() { @@ -141,10 +146,14 @@ If the boilerplate code is too unattractive to you, you may enable the **experim ```javascript class SayHello extends React.Component { + constructor(props) { + super(props); + this.state = { message: 'Hello!' }; + } // WARNING: this syntax is experimental! // Using an arrow here binds the method: handleClick = () => { - alert('Hello!'); + alert(this.state.message); } render() {